2016-04-23 60 views
1

內創建一個新的data.frame使用dfdata.frame一個R函數我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包,我使用BaseflowSeparation功能分離baseflowbfflow

library(EcoHydRology) 
df$bf <- BaseflowSeparation(df$flow, filter_parameter = 0.925, passes = 3) 

該函數創建兩個新列bf.btbf.qft

我想繪製三個參數flow,使用geom_line一個圖形bf.btbf.qft所以我試圖從廣角轉換data.frame長格式使用tidyr

library(tidyr) 
df <- tidyr::gather(df, "parameter", "value", 2:4) 

我得到這個錯誤

Error: Position must be between 0 and n

我檢查df找出BaseflowSeparation函數中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 ... 

任何建議創建兩列的新data.framebf如何獲得BaseflowSeparation函數的輸出爲兩列不是一個新data.frame

+0

使用DF < - cbind(DF,BaseflowSeparation( df $ flow,filter_parameter = 0.925,passes = 3)) – chinsoon12

+0

@ chinsoon12 非常感謝。你能把它寫成答案嗎? – aelwan

+0

@ chinsoon12 如果我有很多網站,並且我正在使用dpyr根據網站進行分組。任何建議如何在dplyr中使用此功能?非常感謝 – aelwan

回答

1

使用dplyr GROUP_BY通過位點進行計算,然後用做從BaseflowSeparation cbind結果與原始data.frame對於每個組,然後取消分組到rbind組

df %>% 
    group_by(site) %>% 
    do(cbind(., BaseflowSeparation(.$flow, filter_parameter = 0.925, passes = 3))) %>% 
    ungroup() 
+0

感謝您的時間和幫助 – aelwan

+0

沒問題!乾杯 – chinsoon12