I have a dataframe df:
colour shape
'red' circle
'blue' square
'blue' circle
'green' sphere
And a double matrix m with named rows/columns
circle square sphere
red 1 4 7
blue 2 5 8
green 3 6 9
I’d like to add a new column to DF such that I obtain:
id colour shape
1 'red' circle
5 'blue' square
2 'blue' circle
9 'green' sphere
I’ve tried doing this with the following code but it doesn’t seem to work:
df$id <- m[df$colour,df$shape]
I’ve also tried apply(); and similar but with no luck. Can anyone tell me the right approach to doing this without using a loop?
I think I might win the shortest answer contest here as long as those are character vectors rather than factors which might be more expected unless you made specifid effort to avoid. It really only adds
cbindto convert the two df “character” vectors to a two column matrix expected by the[.matrixfunction that you were very close to success in using. (And it also seems reasonably expressive.)