Reputation: 171
My data frame df1 is as below
A B
#1 1 3,4
#2 2 5
#3 3 4,1
#4 4 1,3
#5 5 2
i want to replace A and B column numbers with ID's from below data frame DF2
ID DATA
#1 101 data1
#2 503 data2
#3 890 data3
#4 1164 data4
#5 5367 data5
Instead of 1,2,3 ... DF1 should contain data as below ( expected output is just replace the numbers listed in A,B columns with corresponding ID's)
A B
#1 101 890,1164
#2 503 5367
#3 890 1164,101
#4 1164 101,890
#5 5367 503
Is there any way to achieve this?
Upvotes: 0
Views: 83
Reputation: 19544
For the first column it is straight forward:
df1$A <- df2[df1$A,"ID"]
For the second column you have to use strsplit
and paste
because of the multi value column:
df1$B <- sapply(df1$B, function(s)
paste(
df2[strsplit(as.character(s),",")[[1]],"ID"],
collapse=","))
df1
A B
1 101 890,1164
2 503 5367
3 890 1164,101
4 1164 101,890
5 5367 503
Upvotes: 3