rowSums使用间接变量(即使用字符串变量来分配列号) [英] rowSums using an indirect variable (i.e. using a string variable to allocate the column numbers)
问题描述
所以我创建了一个值列表来包含列范围,例如Q1 <-5:9,Q2 < - 10:22等等。阅读原始数据框后,我想创建一个新的Q1作为变量,并且包含总共第5-9列,Q2总共为10:22等。问题是,rowSums不像我一样使用变量来表示实际的范围。
这是我试图实现的,包含原始每周数据的 sval 和 qsval ,包含季度总计:
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)]从每周数据
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])))
}
二?给出的错误信息是:
rowSums中的错误(sval,na.rm = F,get(period [i])) :无效的暗淡
任何建议将不胜感激!谢谢。
在没有可重现的数据的情况下,这里有一个例子,希望你可以适应你的具体情况: p>
set.seed(1)#只是使随机数据可重现
sval< - data.frame(replicate( 6,样品(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 (Qlist,function(x)rowSums(sval [x])))
#Q1 Q2
#1 7 6
#2 6 7
#3 5 5
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, e.g. 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
这篇关于rowSums使用间接变量(即使用字符串变量来分配列号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!