R: How to leave only one value in a string by condition / match?

Viewed 97

I have several concatenated values ​​on one row. For example,

ID    Country    Language

1    Ireland     "English", "French"
2    India       "Indian (Hindi)", "English"
3    Cyprus      "Greek", "Turkish"
4    Canada      "English", "French"

For the strings in the Language column, where besides other values ​​the value "English" is found, I should leave only "English" value.

I want to obtain a such dataset:

ID    Country    Language

1    Ireland     "English"
2    India       "English"
3    Cyprus      "Greek", "Turkish"
4    Canada      "English"

How can I do this with data.table package?

1 Answers

If it is a list column, loop over the list and use an if/else option to return "English" if it is found or else return the vector

library(dplyr)
library(purrr)
df1 %>%
     mutate(Language = map(Language, ~ if("English" %in% .x) "English" else .x))
#  ID Country       Language
#1  1 Ireland        English
#2  2   India        English
#3  3  Cyprus Greek, Turkish
#4  4  Canada        English

Or using data.table

library(data.table)
setDT(df1)[, Language :=  lapply(Language, 
           function(x) if("English" %in% x) "English" else x)]

If it is a single string, use either grep or str_detect

library(stringr)
df2 %>%
     mutate(Language = case_when(str_detect(Language, "English") ~ 
                    "English", TRUE ~  Language))

With data.table

setDT(df2)[grepl("English", Language), Language := "English"]

data

df1 <- structure(list(ID = 1:4, Country = c("Ireland", "India", "Cyprus", 
"Canada"), Language = list(c("English", "French"), c("Indian (Hindi)", 
"English"), c("Greek", "Turkish"), c("English", "French"))), row.names = c(NA, 
-4L), class = "data.frame")
Related