Manipulate Vector and Data Frame in R

Viewed 34
list1=c(1,6,3,4,4,5)
data=data.frame("colA" = c(1:6),
"colB"=c(4,3,1,8,9,8))

I have 'list1' and 'data'

I wish to match the values in 'colB' to the ones in list1 using 'colA' as a key aso it looks like

enter image description here

2 Answers

Perhaps, we need match

data.frame(list1, colB = data$colB[match(list1, data$colA)])
#  list1 colB
#1     1    4
#2     6    8
#3     3    1
#4     4    8
#5     4    8
#6     5    9

You can also use merge, which was one of your tags.

merge(data.frame(list1=list1), data, by.x=c("list1"), by.y="colA")

  list1 colB
1     1    4
2     3    1
3     4    8
4     4    8
5     5    9
6     6    8

Or if you don't care about the column name:

merge(data.frame(colA=list1), data)
  colA colB
1    1    4
2    3    1
3    4    8
4    4    8
5    5    9
6    6    8
Related