In the reprex below I need to assign 'sex' and 'age' values to df2
based on the information contained in df1
; however, the number and order of rows are not the same in the two dataframes, so I cannot use merge()
/ by=
, due to there being multiple rows for some participants (as denoted by 'id'). So, I would need both rows in df2
with an id of 'b' (i.e. rows 1-2) to have a sex of 'F' and an age of 51, then the row with an id of 'd' (row 3) to have a sex of 'F' and an age of 53, etc. Any help would be greatly appreciated. Thank you.
Reprex:
df1<-
data.frame(
id=as.factor(print(letters[1:6])),
sex=as.factor(rep(c("M","F"),3)),
age=as.numeric(50:55)
)
df2<-
data.frame(
id=as.factor(c("b","b","d","c","c","c","a","e","e","f"))
)
In the reprex below I need to assign 'sex' and 'age' values to df2
based on the information contained in df1
; however, the number and order of rows are not the same in the two dataframes, so I cannot use merge()
/ by=
, due to there being multiple rows for some participants (as denoted by 'id'). So, I would need both rows in df2
with an id of 'b' (i.e. rows 1-2) to have a sex of 'F' and an age of 51, then the row with an id of 'd' (row 3) to have a sex of 'F' and an age of 53, etc. Any help would be greatly appreciated. Thank you.
Reprex:
df1<-
data.frame(
id=as.factor(print(letters[1:6])),
sex=as.factor(rep(c("M","F"),3)),
age=as.numeric(50:55)
)
df2<-
data.frame(
id=as.factor(c("b","b","d","c","c","c","a","e","e","f"))
)
Share
Improve this question
asked Feb 4 at 15:34
PhelsumaFLPhelsumaFL
811 silver badge9 bronze badges
1 Answer
Reset to default 2Isn't this what you want? It's exactly what merge
is for..
> merge(df2, df1, by="id",sort = FALSE)
id sex age
1 b F 51
2 b F 51
3 d F 53
4 c M 52
5 c M 52
6 c M 52
7 a M 50
8 e M 54
9 e M 54
10 f F 55