> #just to have some data
> testdata<-matrix(rnorm(14*7),ncol=14)
> testframe<-as.data.frame.matrix(testdata)
>
names(testframe)<-c("Year","Series","Age","WM",
"WF","HM","HF","BM","BF","IM","IF","AM","AF","Yr")> #one way is colSums
> colSums(testframe)[c(3,5,8,10)]
Age WF BM IM
5.024714070 1.974526477 0.004256433 -2.940214886 > #another way is a for loop
> testvector<-rep(NA,14)
> for (i in 1:14) testvector[i]<-sum(testframe[,i])
> testvector[c(3,5,8,10)]
[1] 5.024714070 1.974526477 0.004256433 -2.940214886> #there are other ways:)
<snip>
for(i in 4:13){
sumVar<- sum(popA[,i])
sumVar2<-c(sumVar)
}
<end snip>
You are replacing sumVar in each iteration of the loop, not creating a new
element.
bob
-----Original Message-----
From: Siddique, Amer [mailto:Amer.Siddique@ssa.gov]
Sent: Friday, July 18, 2003 4:02 PM
To: 'r-help@stat.math.ethz.ch'
Subject: [R] create a vector looping over a frame
Hello,
I have a data.frame
> names(popA)
[1] "Year" "Series" "Age" "WM"
"WF" "HM" "HF" "BM"
[9] "BF" "IM" "IF" "AM"
"AF" "Yr"
how do i loop over a subset of variables in this frame to create a vector of
length equal to the number of variables in the subset such that the vector's
ith element is the result of an aggregate fncn applied to the ith variable?
eg,
sumvar<-c(sum(WM),...,sum(AF))
if i try
for(i in 4:13){
sumVar<- sum(popA[,i])
sumVar2<-c(sumVar)
}
it returns
> sumVar2
[1] 287567
> length(sumVar2)
[1] 1
which is only the value at the last spot. i cant quite figure this simple
loop.
Thanks,
Amer Siddique
______________________________________________
R-help@stat.math.ethz.ch mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-help
[[alternative HTML version deleted]]