With the following two data frames
> d1
keystr keynum
1 abc 5
2 def 2
3 def 7
4 abc 3
> d2
HD 2 3 5 7
1 abc H I J K
2 def L M N P
I would like to insert a column d1$val that uses the string in keystr
and the number in keynum
as indices in the d2
data frame. The result should be:
> d1
keystr keynum val
1 abc 5 J
2 def 2 L
3 def 7 P
4 abc 3 I
This should be an indirect application of mapply. How can I make the code below
d1 <- data.frame("keystr"=c("abc","def","def","abc"), "keynum"=c(5,2,7,3))
d2 <- data.frame("HD"=c("abc","def"),
"2"=c("H","L"), "3"=c("I","M"),
"5"=c("J","N"), "7"=c("K","P"))
d1$val <- mapply(function(kstr,knum) d2[kstr,knum],
d1$keystr, d1$keynum )
access the entries in this (indirect) fashion?