[英]How to compare two character vectors in R
> vec
[1] "age" "gpa" "class" "sports"
df <- data.frame(id = c(1232, 2311, 1988), name = c("gpa", "activity", "class"))
> df
id name
1 1232 gpa
2 2311 activity
3 1988 class
I have a vector of items in vec
and I want to compare them to those in df$name
.我在vec
中有一个项目向量,我想将它们与df$name
中的项目进行比较。 For those that exist in df
, I want to create a new data.frame that contains the items vec
and the corresponding id
.对于df
中存在的那些,我想创建一个新的 data.frame ,其中包含项目vec
和相应的id
。 In other words, I want the output to be:换句话说,我希望 output 是:
id name
1 NA age
2 1232 gpa
3 1988 class
4 NA sports
Is there a quick way to do this in R without doing a for loop?有没有一种快速的方法可以在 R 中执行此操作而无需执行 for 循环?
You may use match
您可以使用match
data.frame(id = df$id[match(vec, df$name)], vec)
# id vec
#1 NA age
#2 1232 gpa
#3 1988 class
#4 NA sports
Or merge
the dataframes using left join.或使用左连接merge
数据框。
merge(data.frame(name = vec), df, all.x = TRUE, by = "name")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.