Suppose I have these two dataframes:
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))
As% as_%, I need to retrieve the values of df2
and df2$b0
that match the criteria df2$b1
and df1$med == df2$med
. Then create a new column in df1$trat == df2$trat
whose product is df1
.
I tried this command below, but of course it did not work:
df1$ddap_cm <- df2$b0[df2$med == df1$med & df2$trat == df1$trat] + df2$b1[df1$med == df2$med & df1$trat == df2$trat] * df1$dap_prev
All help is welcome. Thankful.
EDIT:
I ended up finding a very simple solution with dplyr
library(dplyr)
df1 <- left_join(df1, df2, by = c("med", "trat")) # copia as colunas df2$b0 e df2$b1 que cumpram os critérios
df1$ddap_cm <- df1$b0 + (df1$b1*df1$dap_prev)