We can use row/column
indexing to extract the elements from the first dataset and create the ‘result’ column in ‘d2’
d2$result <- d1[-1][cbind(1:nrow(d1), match(d2$mycol, names(d1)[-1]))]
d2
# mycol result
#1 a 40
#2 bxb 88
#3 bxb 76
#4 ct 33
It could be also that there is a single dataset available i.e. ‘d1’ and want to get the ‘d2’. In that case, do a melt
and subset
library(reshape2)
subset(melt(d1, id.var="mycol"), mycol==variable, select= c(1,3))
data
d1 <- data.frame(mycol = c("a", "bxb", "bxb", "ct"), a = c(40, 8, 43, 94),
`bxb` =c(7, 88, 76, 12), ct = c(4,6, 8954, 33), stringsAsFactors=FALSE,
check.names=FALSE)
d2 <- data.frame(mycol = c('a', 'bxb', 'bxb', 'c'), stringsAsFactors=FALSE)
0
solved Matching a value in one column to the name of another column [closed]