【问题标题】:R dplyr::c_across() strange behaviour in rowSumsR dplyr::c_across() rowSums 中的奇怪行为
【发布时间】:2021-09-02 10:47:23
【问题描述】:

我正在尝试了解如何仅将 rowSums() 应用于特定列。 这是一个代表:

df <- tibble(
  "ride" = c("bicycle", "motorcycle", "car", "other"),
  "A" = c(1, NA, 1, NA),
  "B" = c(NA, 2, NA, 2)
)

我可以通过 index[2:3] 得到想要的结果

df %>%
  mutate(total = rowSums(.[2:3], na.rm = TRUE))

# A tibble: 4 × 4
  ride           A     B total
  <chr>      <dbl> <dbl> <dbl>
1 bicycle        1    NA     1
2 motorcycle    NA     2     2
3 car            1    NA     1
4 other         NA     2     2

但是,如果我尝试按名称指定列,则会出现奇怪的结果

df %>%
  mutate(total = sum(c_across(c("A":"B")), na.rm = TRUE))

# A tibble: 4 × 4
  ride           A     B total
  <chr>      <dbl> <dbl> <dbl>
1 bicycle        1    NA     6
2 motorcycle    NA     2     6
3 car            1    NA     6
4 other         NA     2     6

我做错了什么?

我可以通过以下方式实现我想要的:

df %>%
  mutate_all(~replace(., is.na(.), 0)) %>%
  mutate(total = A + B)

但我想通过传递一个向量来指定列名,这样我以后可以更改为不同的列名组合。 这样的事情是我想要实现的:

cols_to_sum <- c("A","B")

df %>%
  mutate(total = sum(across(cols_to_sum), na.rm = TRUE))

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    您可以使用select 指定您想要sum 的列。

    library(dplyr)
    
    cols_to_sum <- c("A","B")
    
    df %>%
      mutate(total = rowSums(select(., all_of(cols_to_sum)), na.rm = TRUE))
    
    #  ride           A     B total
    #  <chr>      <dbl> <dbl> <dbl>
    #1 bicycle        1    NA     1
    #2 motorcycle    NA     2     2
    #3 car            1    NA     1
    #4 other         NA     2     2
    

    c_acrossrowwise 一起使用 -

    df %>%
      rowwise() %>%
      mutate(total = sum(c_across(all_of(cols_to_sum)), na.rm = TRUE)) %>%
      ungroup
    

    【讨论】:

    • 我一直在学习 dplyr 1.0 中的新功能,可能一直让自己感到困惑哈哈。感谢您提供清晰的示例,祝您有愉快的一天!
    • rowSums(across(all_of(cols_to_sum))) 是另一个选项,而不是 select
    猜你喜欢
    • 1970-01-01
    • 2015-06-26
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多