有没有办法使用指定变量的获取行总和
Is there a way to use get row sums with specified variables
我想获取总和行但不包括给定行。列出所有变量有点乏味。我想按位置突出显示要在操作中排除的变量。有什么想法吗?
library(tidyverse)
df <- tribble(
~"var1", ~"var2", ~"var3", ~"var4",
"A", 20, 10, 23,
"B", 30, 6, 34,
"C", 40, 8, 23,
"D", 50, 10, 24
)
# This is the desired output
df %>%
rowwise() %>%
mutate(total = sum(var2, var3, var4))
你可以使用基础 R:
df$total <- rowSums(df[, 2:4])
df
#> # A tibble: 4 x 5
#> var1 var2 var3 var4 total
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 A 20 10 23 53
#> 2 B 30 6 34 70
#> 3 C 40 8 23 71
#> 4 D 50 10 24 84
由 reprex package (v2.0.1)
于 2022-02-05 创建
这是一个 dplyr
解决方案,它使用 select
:
df %>%
mutate(total = rowSums(select(., -var1)))
var1 var2 var3 var4 total
<chr> <dbl> <dbl> <dbl> <dbl>
1 A 20 10 23 53
2 B 30 6 34 70
3 C 40 8 23 71
4 D 50 10 24 84
我想获取总和行但不包括给定行。列出所有变量有点乏味。我想按位置突出显示要在操作中排除的变量。有什么想法吗?
library(tidyverse)
df <- tribble(
~"var1", ~"var2", ~"var3", ~"var4",
"A", 20, 10, 23,
"B", 30, 6, 34,
"C", 40, 8, 23,
"D", 50, 10, 24
)
# This is the desired output
df %>%
rowwise() %>%
mutate(total = sum(var2, var3, var4))
你可以使用基础 R:
df$total <- rowSums(df[, 2:4])
df
#> # A tibble: 4 x 5
#> var1 var2 var3 var4 total
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 A 20 10 23 53
#> 2 B 30 6 34 70
#> 3 C 40 8 23 71
#> 4 D 50 10 24 84
由 reprex package (v2.0.1)
于 2022-02-05 创建这是一个 dplyr
解决方案,它使用 select
:
df %>%
mutate(total = rowSums(select(., -var1)))
var1 var2 var3 var4 total
<chr> <dbl> <dbl> <dbl> <dbl>
1 A 20 10 23 53
2 B 30 6 34 70
3 C 40 8 23 71
4 D 50 10 24 84