I have two (example) data.frames (df1, df2)
#df1
L <- LETTERS[1:4]
b <- sample(L, 20, replace = TRUE)
df1 <- data.frame(stuff1 = 1, stuff2 = 1:10, b = b, c= NA, stringsAsFactors=FALSE)
#df2
a <- c(10,20,30,40)
df2 <- data.frame(xx = L, yy = a, stringsAsFactors=FALSE )
i want to have a new column, let's say c
, in df1
based on the values out of df2
. One example: A
has the corresponding value of 10 (see df2
) so for every A in column b
of df1
should be 10 written down in the (new) line c
. And this for every row of xx
in df2
, so in this case A,B,C and D. My code is not really working and is based only for a single value, here A
:
##copy column b now it is c
df1["c"] <- df1$b
# which value has A in df2?
zz <- df2[df2$xx == "A",]
xy <- zz$yy
# fill in the new value in c (this is not working)
df1[df1$c == "A", ] <- xy
i hope it is clear what i want to say... oh and i have some big data this is only an example to try out...