dplyr::coalesce在R中跳过不存在的值

huangapple go评论78阅读模式
英文:

dplyr::coalesce skip non-existent values in R

问题

dplyr::coalesce()函数可以跳过不存在的值,比如在这个例子中的列名(例如col2data中不存在)。

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)))
  )

如果col1coln是连续的,你可以简单地使用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 &lt;- paste0(&quot;col&quot;, 1:10)
# [1] &quot;col1&quot;  &quot;col2&quot;  &quot;col3&quot;  &quot;col4&quot;  &quot;col5&quot;  &quot;col6&quot;  &quot;col7&quot;  &quot;col8&quot;  &quot;col9&quot;  &quot;col10&quot;

data %&gt;%
  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 %&gt;%
  mutate(
    var_1 = do.call(coalesce, pick(col1:col10))
  )

huangapple
  • 本文由 发表于 2023年7月27日 17:04:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76778152.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定