Newbie using R, and would like to know how to create a new column in a data frame based on data from another data frame. Suppose I have 2 data frames, linked by letters "a", "b", and "c" in df1
col2
and df2
col1
as follows:
> col1<-c(1, 2, 3, 4)
> col2<-c("a","b","c","c")
> df1<-data.frame(col1, col2)
> df1
col1 col2
1 1 a
2 2 b
3 3 c
4 4 c
> c1<-c("a","b","c")
> c2<-c("Jim","Sue","Bob")
> c3<-c("abc","def","ghi")
> df2<-data.frame(c1,c2,c3)
> df2
c1 c2 c3
1 a Jim abc
2 b Sue def
3 c Bob ghi
I want to add a column3 to df1
to add user names based on the values of "a", "b", or "c" in df1
. That is, how do I get the following using R?
> df1
col1 col2 col3
1 1 a Jim
2 2 b Sue
3 3 c Bob
4 4 c Bob
I've tried df1["col3"]<-df2[df1$col2==df2$c1]$c2
but it's not working.
Note: I only want to add one column from df2
to df
as shown above (e.g. not all columns in df2
).