简体   繁体   中英

Check if one column's values are contained within another column's in R dataframes and then add the contained column as a new column

I have this dataframes

D1$document = Emily 1.1.1.1. D2$user_name = Emily

I wish to match whether D2 to D1, and if D2$user_name column value (by row) is contained within the D1$document value by row too, then add D2$user_name corresponding value found in a new column in D1 called also D1$user_name.

I have tried str_detect, match etc but I can't seem to get it right?

unigram_data$user_name <- unigram_data %>% mutate(user_name = ifelse(str_detect(as.character(unigram_data$document)
                                , as.character(review_corpus$user_name)), 
                                cbind(user_name = review_corpus$user_name),
                                NA
                                ))

Thank you!

Yea, it's really impossible to give you exact advise without a reproducible minimal example. However, here is a general example using case_when and str_detect

dplyr::starwars %>% 
  select(name,homeworld,species) %>% 
  mutate(IsHuman = str_detect(species,'Human')) %>% 
  mutate(HumanFromNaboo = case_when(
    species == 'Human' & IsHuman == T ~ T,
    T ~ F
  ))

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