简体   繁体   中英

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 . For those that exist in df , I want to create a new data.frame that contains the items vec and the corresponding id . In other words, I want the output to be:

    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?

You may use 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(data.frame(name = vec), df, all.x = TRUE, by = "name")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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