[R] why order doesn't work?
Bert Gunter
gunter.berton at gene.com
Fri Jul 27 22:54:07 CEST 2012
This has nothing to do with order(). The following also reproduces the behavior:
> test <- data.frame(x=letters[1:5],y = 1:5)
> test[1:5,]$z <- 11:15
Warning message:
In `[<-.data.frame`(`*tmp*`, 1:5, , value = list(x = 1:5, y = 1:5, :
provided 3 variables to replace 2 variables
> test
x y
1 a 1
2 b 2
3 c 3
4 d 4
5 e 5
> test$z <- 11:15
> test
x y z
1 a 1 11
2 b 2 12
3 c 3 13
4 d 4 14
5 e 5 15
I don't know what's going on here, but it appears that it has
something to do (again!) with the $ convenience syntax, which is best
avoided, it seems. Instead of the rather convoluted syntax of the
first statement, note that
> test <- data.frame(x=letters[1:5],y = 1:5)
> test[1:5,"z"] <- 11:15
> test
x y z
1 a 1 11
2 b 2 12
3 c 3 13
4 d 4 14
5 e 5 15
... works fine.
Have you read "An Intro to R" where indexing is discussed? If not,
why not? If so, please follow it. It will help you avoid such
difficulties.
-- Bert
On Fri, Jul 27, 2012 at 1:22 PM, cowboy <dgecon at gmail.com> 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?
> thanks,
> Guang
>
> ______________________________________________
> R-help at 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.
--
Bert Gunter
Genentech Nonclinical Biostatistics
Internal Contact Info:
Phone: 467-7374
Website:
http://pharmadevelopment.roche.com/index/pdb/pdb-functional-groups/pdb-biostatistics/pdb-ncb-home.htm
More information about the R-help
mailing list