简体   繁体   中英

rowSums using an indirect variable (i.e. using a string variable to allocate the column numbers)

I'm still pretty much a newbie in R but enjoying the journey so far. I'm trying to group weekly columns together into quarters, and try to create a more elegant solution rather than creating separate lines to assign values.

So I have created a list of values to contain the column ranges, eg Q1 <- 5:9, Q2 <- 10:22, and so forth. After reading the original data frame, I want to create a new one that has Q1 as the variable, and contains the total of column 5-9, Q2 with the total of 10:22, etc. The problem is, rowSums doesn't like me using a variable to denote the actual range.

This is what I am trying to achieve, with sval containing the original weekly data, and qsval , containing the quarterly totals:

Q110 <- 5:9
Q210 <- 10:22
Q310 <- 23:35
Q410 <- 36:48

Q111 <- 49:61
Q211 <- 62:74
Q311 <- 75:87
Q411 <- 88:100

qsval <- sval[,c(1:4)]   # Copying the first four columns from the weekly data
period <- c('Q110','Q210','Q310','Q410','Q111','Q211','Q311','Q411')

for (i in 1:8) {
    assign(qsval$period[i], rowSums(sval,na.rm=F, get(period[i])))
}

Is this possible at all? The error message given is:

Error in rowSums(sval, na.rm = F, get(period[i])) : invalid 'dims' 

Any advice would be much appreciated! Thank you.

In the absence of reproducible data, here's an example which hopefully you can adapt to your specific case:

set.seed(1) # just to make the random data reproducible
sval <- data.frame(replicate(6,sample(1:3)))

#  X1 X2 X3 X4 X5 X6
#1  1  3  3  1  3  2
#2  3  1  2  3  1  3
#3  2  2  1  2  2  1

Qlist <- list(Q1=1:3,Q2=4:6)
qsval <- data.frame(lapply(Qlist, function(x) rowSums(sval[x]) ))

#  Q1 Q2
#1  7  6
#2  6  7
#3  5  5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM