R函数在我的data.frame内创建一个新的data.frame [英] R function creates a new data.frame within my data.frame
问题描述
使用 df
data.frame
set.seed(123)
date <- as.Date(seq(as.Date("2003-01-01"), as.Date("2008-05-31"), by = 1), format="%Y-%m-%d")
flow <- runif(1978, 48530, 1250365)
df <- data.frame(date, flow)
和 EcoHydRology
我从流分开
baseflow
bf
使用 BaseflowSeparation
函数。
library(EcoHydRology)
df$bf <- BaseflowSeparation(df$flow, filter_parameter = 0.925, passes = 3)
该函数创建两个新列 bf.bt
和 bf.qft
The function creates two new columns bf.bt
and bf.qft
我想绘制三个参数 flow
, bf.bt
和 bf.qft
在一个图上使用 geom_line
所以我尝试转换data.frame从广泛到长格式使用 tidyr
I wanted to plot the three parameters flow
, bf.bt
and bf.qft
on one graph using geom_line
so I tried converting the data.frame from wide to long format using tidyr
library(tidyr)
df <- tidyr::gather(df, "parameter", "value", 2:4)
我收到这个错误
错误:位置必须介于0和n之间
我检查了 df
以找出 BaseflowSeparation
函数在 df
data.frame bf
>
I checked df
to find out that BaseflowSeparation
function created new data.frame
bf
of two columns within df
> str(df)
'data.frame': 1978 obs. of 3 variables:
$ date: Date, format: "2003-01-01" "2003-01-02" "2003-01-03" ...
$ flow: num 394151 995943 540053 1109771 1178816 ...
$ bf :'data.frame': 1978 obs. of 2 variables:
..$ bt : num 168374 171233 172381 150429 120018 ...
..$ qft: num 178506 824710 367671 959342 1058798 ...
任何建议如何将 BaseflowSeparation
函数的输出作为两列不是新的code> data.frame ?
Any suggestion how to get the output of BaseflowSeparation
function as two columns not a new data.frame
?
推荐答案
使用dplyr group_by按网站进行计算,使用do来将BaseflowSeparation的结果与原始数据cbind结合起来,然后取消组合为rbind组
Use dplyr group_by to perform calculation by site, then use do to cbind results from BaseflowSeparation with original data.frame for each group then ungroup to rbind groups
df %>%
group_by(site) %>%
do(cbind(., BaseflowSeparation(.$flow, filter_parameter = 0.925, passes = 3))) %>%
ungroup()
这篇关于R函数在我的data.frame内创建一个新的data.frame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!