Match character vector in a dataframe with another

2019-05-11 04:09发布

问题:

Here is a dataframe and a vector.

df1  <-  tibble(var1 = c("abcd", "efgh", "ijkl", "qrst"))

vec <-  c("abcd", "mnop", "ijkl")

Now, for all the values in var1 that matches with the values in vec, keep only first 3 characters in var1 such that the desired solution is:

df2 <- tibble(var1 = c("abc", "efgh", "ijk", "qrst"))

Since, "abcd" matches, we keep only 3 characters i.e. "abc" in df2, but "efgh" doesn't exist in vec, so we keep it as is i.e "efgh" in df2.

How can I use dplyr and/or stringr to accomplish this?

回答1:

You can just use %in% to check whether the strings are in the vector, and substr to trim the vector:

df1 %>% 
    mutate(var1 = ifelse(var1 %in% vec, substr(var1, 1, 3), var1))

# A tibble: 4 x 1
#  var1 
#  <chr>
#1 abc  
#2 efgh 
#3 ijk  
#4 qrst