3
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))
In df2
need to recover the values of df2$b0
and df2$b1
which meet the criteria df1$med == df2$med
and df1$trat == df2$trat
. Next create a new column in df1
whose product is df2$b0 + df2$b1 * df1$dap_prev
.
I tried with this command below, but of course it didn’t 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. Grateful.
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)
In the command you made there is a typo
df.1$trat
when I believe you wanted to saydf1$trat
. Test and see if it fulfills the order!– Flavio Silva
As Flavio said, I think the problem was only in the typo itself
– Rafael Cunha
How is it that
df1$dap_prev
is not indexed by logical conditions?– Rui Barradas