我正在尝试了解如何将rowSums()仅应用于特定的列。这是一个重述:
df <- tibble(
"ride" = c("bicycle", "motorcycle", "car", "other"),
"A" = c(1, NA, 1, NA),
"B" = c(NA, 2, NA, 2)
)我可以通过索引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))发布于 2021-09-02 10:51:13
您可以使用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 2c_across与rowwise协同工作-
df %>%
rowwise() %>%
mutate(total = sum(c_across(all_of(cols_to_sum)), na.rm = TRUE)) %>%
ungrouphttps://stackoverflow.com/questions/69028784
复制相似问题