有条件地计算两个数据帧之间的操作输出

时间:2017-10-04 14:29:20

标签: r dataframe

假设我有这两个数据帧:

set.seed(123)
df1<-data.frame(rep=rep(1:4,each=360),parc=rep(1:40,each=36),trat=rep(sample(1:10),each=36),tree=rep(1:36,40),med=1,dap_prev=rnorm(1440, mean = 12))
df2<-data.frame(med=rep(1:18,each=10),trat=rep(sample(1:10)),b0=rnorm(180),b1=rnorm(180))

df2中,当符合条件df2$b0df2$b1时,我需要检索df1$med == df2$meddf1$trat == df2$trat的值。然后在df1中创建一个新列,其产品为df2$b0 + df2$b1 * df1$dap_prev

我尝试使用下面的命令,但当然它不起作用:

df1$ddap_cm <- df2$b0[df2$med == df1$med & df2$trat == df.1$trat] + df2$b1[df1$med == df2$med & df1$trat == df2$trat] * df1$dap_prev

1 个答案:

答案 0 :(得分:0)

我不确定我是否正确,所以我建议这两步回答

set.seed(123)
df1<-data.frame(rep=rep(1:4,each=360),parc=rep(1:40,each=36),trat=rep(sample(1:10),each=36),tree=rep(1:36,40),med=1,dap_prev=rnorm(1440, mean = 12))
df2<-data.frame(med=rep(1:18,each=10),trat=rep(sample(1:10)),b0=rnorm(180),b1=rnorm(180))

### Answer
library(dplyr)
df1_v2 <- left_join(df1, df2, by = c("med", "trat")) # matching with "med" and "trat"
df1_v2$ddap_cm <- df1_v2$b0 + (df1_v2$b1*df1_v2$dap_prev) # new variable
str(df1_v2)