简体   繁体   English

在 R 中操作向量和数据帧

[英]Manipulate Vector and Data Frame in R

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'我有“list1”和“data”

I wish to match the values in 'colB' to the ones in list1 using 'colA' as a key aso it looks like我希望使用 'colA' 作为键将 'colB' 中的值与 list1 中的值相匹配,它看起来像

在此处输入图片说明

Perhaps, we need match也许,我们需要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 ,这是您的标签之一。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM