英文:
dplyr::coalesce skip non-existent values in R
问题
dplyr::coalesce()函数可以跳过不存在的值,比如在这个例子中的列名(例如col2在data中不存在)。
data %>%
mutate(
var_1 = coalesce(col1, col2,...,coln),
var_n = ...)
谢谢!
英文:
Is it actually possible to have dplyr::coalesce() skip non-existent values like e.g. colnames in this case? (e.g. col2 doesn't exist in data)
data %>%
mutate(
var_1 = coalesce(col1, col2,...,coln),
var_n = ...)
Thanks
答案1
得分: 2
你可以提前将所有可能的列名存储在一个字符向量中,然后使用any_of()函数来选择列。如果某些列名不存在,any_of()函数会跳过它们。
library(dplyr)
vars <- paste0("col", 1:10)
# [1] "col1" "col2" "col3" "col4" "col5" "col6" "col7" "col8" "col9" "col10"
data %>%
mutate(
var_1 = do.call(coalesce, pick(any_of(vars)))
)
如果col1到coln是连续的,你可以简单地使用col1:coln来选择位于左边的col1和右边的coln之间的变量。
data %>%
mutate(
var_1 = do.call(coalesce, pick(col1:col10))
)
英文:
You can store all possible column names into a character vector in advance, then use any_of() to select columns. If some column names do not exist, any_of() will skip them.
library(dplyr)
vars <- paste0("col", 1:10)
# [1] "col1" "col2" "col3" "col4" "col5" "col6" "col7" "col8" "col9" "col10"
data %>%
mutate(
var_1 = do.call(coalesce, pick(any_of(vars)))
)
If col1 to coln are in sequence, you can simply use col1:coln to select variables lying between col1 on the left and coln on the right.
data %>%
mutate(
var_1 = do.call(coalesce, pick(col1:col10))
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论