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

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

dplyr::coalesce skip non-existent values in R

问题

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

  1. data %>%
  2. mutate(
  3. var_1 = coalesce(col1, col2,...,coln),
  4. 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)

  1. data %>%
  2. mutate(
  3. var_1 = coalesce(col1, col2,...,coln),
  4. var_n = ...)

Thanks

答案1

得分: 2

你可以提前将所有可能的列名存储在一个字符向量中,然后使用any_of()函数来选择列。如果某些列名不存在,any_of()函数会跳过它们。

  1. library(dplyr)
  2. vars <- paste0("col", 1:10)
  3. # [1] "col1" "col2" "col3" "col4" "col5" "col6" "col7" "col8" "col9" "col10"
  4. data %>%
  5. mutate(
  6. var_1 = do.call(coalesce, pick(any_of(vars)))
  7. )

如果col1coln是连续的,你可以简单地使用col1:coln来选择位于左边的col1和右边的coln之间的变量。

  1. data %>%
  2. mutate(
  3. var_1 = do.call(coalesce, pick(col1:col10))
  4. )
英文:

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.

  1. library(dplyr)
  2. vars &lt;- paste0(&quot;col&quot;, 1:10)
  3. # [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;
  4. data %&gt;%
  5. mutate(
  6. var_1 = do.call(coalesce, pick(any_of(vars)))
  7. )

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.

  1. data %&gt;%
  2. mutate(
  3. var_1 = do.call(coalesce, pick(col1:col10))
  4. )

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:

确定