> test<-data.frame(cbind(x=c(3,5,2,6,7),y=c(8,1,4,9,0))) > test[order(test$x),]$sumy<-cumsum(test[order(test$x),]$y)
is asking a bit too much of R. If you add the line test$sumy <- numeric(nrow(test)) between those lines you get what you want. Here are the details. The nested replacement expression dataFrame[subscript, ]$component <- value is treated as the sequence of expressions TMP <- dataFrame[subscript,] TMP$component <- value dataFrame[subscript, ] <- TMP If dataFrame has no column named 'component' then the last expression involves trying to replace some rows of the n-column data.frame dataFrame by the contents of the (n+1)-column data.frame TMP and R will not do that. By the way, drop the cbind from data.frame(cbind(x=..., y=...)) and just use data.frame(x=..., y=...) The cbind() slows things down, wastes memory, and can give surprising results (when x and y have different classes). Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com > -----Original Message----- > From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On > Behalf Of cowboy > Sent: Friday, July 27, 2012 1:23 PM > To: r-help@r-project.org > Subject: [R] why order doesn't work? > > hi all, > I want to get a cumsum according to the order of some variable. > However, it doesnt' work. > For example, > ********************** > test<-data.frame(cbind(x=c(3,5,2,6,7),y=c(8,1,4,9,0))) > test[order(test$x),]$sumy<-cumsum(test[order(test$x),]$y) > ********************** > R complians Warning message: > In `[<-.data.frame`(`*tmp*`, order(test$x), , value = list(x = c(2, : > provided 3 variables to replace 2 variables. > > while the following > *********************** > test$sumy<-cumsum(test[order(test$x),]$y) > ****************** > gives > x y sumy > 1 3 8 4 > 2 5 1 12 > 3 2 4 13 > 4 6 9 22 > 5 7 0 22 > > should it gives > > x y sumy > 1 3 8 12 > 2 5 1 13 > 3 2 4 4 > 4 6 9 22 > 5 7 0 22 > > What am I missing here? > thanks, > Guang > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.