我有以下精简数据集:
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="")]]
}
我想总结Var1和Var2列,我使用:
a$sum<-a$Var_1 + a$Var_2
实际上我的数据集要大得多 - 我想从Var_1求和到Var_n(n可以高达20)。必须有一种更有效的方法来做到这一点:
a$sum<-a$Var_1 + ... + a$Var_n
答案 0 :(得分:15)
您可以使用colSums(a[,c("Var1", "Var2")])
或rowSums(a[,c("Var_1", "Var_2")])
。在你的情况下你想要这封信。
答案 1 :(得分:8)
这是使用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
由reprex package(v0.2.1)于2019-01-01创建
答案 2 :(得分:1)
如果要处理非常大的数据集,rowSums
可能会很慢。
另一个选择是Rfast包中的rowsums
函数。这要求您在此过程中将数据转换为matrix
,并使用列索引而不是名称。这是一个基于您的代码的示例:
## load Rfast
library(Rfast)
## create dataset
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="")]]
}
## get column indices based on names
col_st <- grep("Var_1", colnames(a)) # index of "Var_1" col
col_en <- grep("Var_2", colnames(a)) # index of "Var_2" col
cols <- c(col_st:col_en) # indices of all cols from "Var_1" to "Var_2"
## sum rows 4 to 5
a$Total <- rowsums(as.matrix(a[,cols]))
答案 3 :(得分:0)
你可以使用 dplyr
a %>%
rowwise() %>%
mutate(sum = sum(Col1,Col1, na.rm = T))
或更高效
a %>%
rowwise() %>%
mutate(sum = sum(across(starts_with("Col")), na.rm = T))