[R] How to avoid two for loops?
conglan
lingyi.ma at gmail.com
Wed Feb 25 10:08:58 CET 2015
HI,
I have the following large data set:
the sample is as the following:
Country Product Brand Year_Month DisplaySize OperationSystem
AE 1 20 201204 1 1
AE 5 20 201204 1 1
AE 2 28 201204 3 2
AE 3 27 201204 1 1
AE 1 20 201205 1 1
AE 2 28 201205 3 2
AE 4 20 201205 1 2
I want to calculate the extra three columns as the following:
Let's say "20" is own brand
#The sums of display size produced by competing brand
#The sums of display size of other products produced by own brand
#The sums of display size of products of competing firm in the same
operating system
I build up the following codes, apprently two loop takes too long time:
dd<-unique(cl$Year_Month)
fldata<-data.frame(NULL)
for ( i in 1:length(dd)){
cls<-cl[cl$Year_Month==dd[i],]
ws<-numeric(0) #The sums of characteristics of products produced by
competing firms
ws1<-numeric(0) #The sums of characteristics of other products produced
by firm
ws2<-numeric(0) #The sums of characteristics of products of competing
firm in the same operating system
for (j in 1:dim(cls)[1]){
wd<-sum(cls[cls$Brand!=cls$Brand[j],]$DISPLAY_SIZE_INCH)
ws[j]<-wd
wc<-sum(cls[cls$Brand==cls$Brand[j] & cls$Item_Id!=cls$Item_Id[j]
,]$DISPLAY_SIZE_INCH)
ws1[j]<-wc
wf<-sum(cls[cls$Brand!=cls$Brand[j] &
cls$OPERATING_SYST==cls$OPERATING_SYST[j]
,]$DISPLAY_SIZE_INCH)
ws2[j]<-wf
}
cls<-cbind(cls,SumPCf=ws,SumOPf=ws1,SumPCfOp=ws2)
fldata<-rbind(fldata,cls)
}
how can I avoid two loops and improve the speed of my code??????? any other
solution?
Thanks.
Tammy
--
View this message in context: http://r.789695.n4.nabble.com/How-to-avoid-two-for-loops-tp4703799.html
Sent from the R help mailing list archive at Nabble.com.
[[alternative HTML version deleted]]
More information about the R-help
mailing list