[R] why order doesn't work?

Berend Hasselman bhh at xs4all.nl
Fri Jul 27 22:52:15 CEST 2012


cowboy wrote
> 
> 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?
> 

order is working just fine.
Apparently one cannot create a new column in a data.frame with the $
notation.
This will work

test[order(test$x),"sumy"]<-cumsum(test[order(test$x),]$y)

Berend




--
View this message in context: http://r.789695.n4.nabble.com/why-order-doesn-t-work-tp4638149p4638152.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list