在R中的多个列中有效地求和

use*_*648 16 r sum

我有以下精简数据集:

a<-as.data.frame(c(2000:2005))
a$Col1<-c(1:6)
a$Col2<-seq(2,12,2)

colnames(a)<-c("year","Col1","Col2")

for (i in 1:2){
  a[[paste("Var_", i, sep="")]]<-i*a[[paste("Col", i, sep="")]]
}
Run Code Online (Sandbox Code Playgroud)

我想总结列Var1和Var2,我使用:

a$sum<-a$Var_1 + a$Var_2
Run Code Online (Sandbox Code Playgroud)

实际上我的数据集要大得多 - 我想将Var_1与Var_n相加(n可以达到20).必须有一种更有效的方法来做到这一点:

 a$sum<-a$Var_1 + ... + a$Var_n
Run Code Online (Sandbox Code Playgroud)

pso*_*res 15

你可以使用colSums(a[,c("Var1", "Var2")])rowSums(a[,c("Var_1", "Var_2")]).在你的情况下你想要后者.


Jos*_*ana 13

与 dplyr 你可以使用

a %>%
rowwise() %>%
mutate(sum = sum(Col1,Col1, na.rm = T))
Run Code Online (Sandbox Code Playgroud)

或更有效地

a %>%
rowwise() %>%
mutate(sum = sum(across(starts_with("Col")), na.rm = T))
Run Code Online (Sandbox Code Playgroud)


Mat*_*cho 12

这是使用的解决方案tidyverse。您可以使用select()函数在内选择适当的列,将其扩展为任意多的列mutate()

library(tidyverse)

a<-as.data.frame(c(2000:2005))
a$Col1<-c(1:6)
a$Col2<-seq(2,12,2)

colnames(a)<-c("year","Col1","Col2")

for (i in 1:2){
    a[[paste("Var_", i, sep="")]]<-i*a[[paste("Col", i, sep="")]]
}
a
#>   year Col1 Col2 Var_1 Var_2
#> 1 2000    1    2     1     4
#> 2 2001    2    4     2     8
#> 3 2002    3    6     3    12
#> 4 2003    4    8     4    16
#> 5 2004    5   10     5    20
#> 6 2005    6   12     6    24

# Tidyverse solution
a %>%
    mutate(Total = select(., Var_1:Var_2) %>% rowSums(na.rm = TRUE))
#>   year Col1 Col2 Var_1 Var_2 Total
#> 1 2000    1    2     1     4     5
#> 2 2001    2    4     2     8    10
#> 3 2002    3    6     3    12    15
#> 4 2003    4    8     4    16    20
#> 5 2004    5   10     5    20    25
#> 6 2005    6   12     6    24    30
Run Code Online (Sandbox Code Playgroud)

reprex软件包(v0.2.1)创建于2019-01-01