我想在不同的列中找到一个单词并在新的列中对其进行变异。
“数据”是一个例子,“目标”是我想要的。我尝试了很多,但没有得到工作。
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)
对于您提供的数据结构,我们可以使用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)
| 归档时间: |
|
| 查看次数: |
376 次 |
| 最近记录: |