从新列中的多列中提取字符串

Jan*_*tz 4 r stringr dplyr

我想在不同的列中找到一个单词并在新的列中对其进行变异。

“数据”是一个例子,“目标”是我想要的。我尝试了很多,但没有得到工作。

 library(dplyr)
 library(stringr)

 data <- tibble(
    component1 = c(NA, NA, "Word", NA, NA, "Word"),
    component2 = c(NA, "Word", "different_word", NA, NA, "not_this")
    )

 goal <- tibble(
    component1 = c(NA, NA, "Word", NA, NA, "Word"),
    component2 = c(NA, "Word", "different_word", NA, NA, "not_this"),
    component = c(NA, "Word", "Word", NA, NA, "Word")
    )


not_working <- data %>%
     mutate(component = across(starts_with("component"), ~ str_extract(.x, "Word")))
Run Code Online (Sandbox Code Playgroud)

Tar*_*Jae 7

对于您提供的数据结构,我们可以使用coalesce

library(dplyr)

data %>% 
  mutate(component = coalesce(component1, component2))
Run Code Online (Sandbox Code Playgroud)
component1 component2     component
  <chr>      <chr>          <chr>    
1 NA         NA             NA       
2 NA         Word           Word     
3 Word       different_word Word     
4 NA         NA             NA       
5 NA         NA             NA       
6 Word       not_this       Word     
Run Code Online (Sandbox Code Playgroud)

  • 这在 component1 是“ different_word”而 component2 是“Word”的情况下不起作用。尽管非常简洁,但我不确定这个答案是否适用于所有情况。 (3认同)
  • 这很漂亮! (2认同)