Home > Blockchain >  How to compare two character vectors in R
How to compare two character vectors in R

Time:08-12

> 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?

CodePudding user response:

You can just call data.frame and use value matching with ifelse and %in%

data.frame(id = ifelse(vec %in% df$name, df$id, NA),  name = vec)

    id   name
1   NA    age
2 2311    gpa
3 1988  class
4   NA sports

CodePudding user response:

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")
  • Related