rowwise() 与 dplyr 中的列名向量求和

MKR*_*MKR 7 r dplyr rlang

我再次对如何实现这一目标感到困惑:

鉴于此数据框:

df <- tibble(
  foo = c(1,0,1),
  bar = c(1,1,1),
  foobar = c(0,1,1)
)
Run Code Online (Sandbox Code Playgroud)

这个向量:

to_sum <- c("foo", "bar")
Run Code Online (Sandbox Code Playgroud)

我想获得列中值的行式总和to_sum

期望的输出:

# A tibble: 3 x 4
# Rowwise: 
    foo   bar foobar   sum
  <dbl> <dbl>  <dbl> <dbl>
1     1     1      0     2
2     0     1      1     1
3     1     1      1     2
Run Code Online (Sandbox Code Playgroud)

输入它是有效的(显然)。

df %>% rowwise() %>% 
  mutate(
    sum = sum(foo, bar)
  )
Run Code Online (Sandbox Code Playgroud)

这不会:

df %>% rowwise() %>% 
  mutate(
    sum = sum(to_sum)
  )
Run Code Online (Sandbox Code Playgroud)

我理解,因为如果我要尝试:

df %>% rowwise() %>% 
  mutate(
    sum = sum("foo", "bar")
  )
Run Code Online (Sandbox Code Playgroud)

如何从列名向量计算行式总和?

use*_*230 5

我认为您正在寻找rlang::syms将字符串强制为 quosures:

library(dplyr)
library(rlang)
df %>% 
  rowwise() %>% 
  mutate(
    sum = sum(!!!syms(to_sum))
  )
#     foo   bar foobar   sum
#   <dbl> <dbl>  <dbl> <dbl>
# 1     1     1      0     2
# 2     0     1      1     1
# 3     1     1      1     2
Run Code Online (Sandbox Code Playgroud)


Sam*_*rke 5

library(janitor)
df %>%
  adorn_totals("col",,,"sum",to_sum)

 foo bar foobar sum
   1   1      0   2
   0   1      1   1
   1   1      1   2
Run Code Online (Sandbox Code Playgroud)

为什么,,,

如果您查看?adorn_totals,您会看到它的参数:

adorn_totals(dat, where = "row", fill = "-", na.rm = TRUE, name = "Total", ...)

最后一个...是控制列选择。不幸的是,没有办法直接告诉 Rto_sum应该用于那个...参数,所以,,,在这个答案中是告诉它使用参数的默认值where,fill,na.rm。在这一点上,它具有除 之外的每个参数的值...,因此to_sum适用于它。

该主题将在此处进一步讨论:在调用 tidyselect-using 函数时指定 dots 参数,而无需指定前面的参数

  • 是的,我刚刚在解释它的答案中添加了更多内容。 (2认同)