[R] sapply behavior

Douglas Bates bates at stat.wisc.edu
Tue Sep 28 03:13:13 CEST 2004


Elizabeth Purdom wrote:

> I use sapply very frequently, but I have recently noticed a behavior of 
> sapply which I don't understand and have never seen before. Basically, 
> sapply returns what looks like a matrix,  says it a matrix, and appears 
> to let me do matrix things (like transpose). But it is also a list and 
> behaves like a list when I subset it, not a vector (so I can't sort a 
> row for instance). I don't know where this is coming from so as to avoid 
> it, nor how to handle the beast that sapply is returning. I double 
> checked my old version of R and apparently this same thing happens in 
> 1.8.0, though I never experienced it. I had a hard time reproducing it, 
> and I don't know what's setting it off, but the code below seems to do 
> it for me. (I'm using R on Windows XP, either 1.8.0 or 1.9.1)
> 
> Thanks for any help,
> Elizabeth Purdom
> 
> 
>  > temp2<-matrix(sample(1:6,6,replace=F),byrow=F,nrow=6,ncol=4)
>  > colnames(temp2)<-paste("A",as.character(1:4),sep="")
>  > temp2<-as.data.frame(temp2)

It is this coercion to the data frame that is injecting a list-like 
property into the result.  Try your script without that line and it will 
work as you expect.

>  > newtemp2<-sapply((1:6),function(x){xmat<-temp2[temp2[,1]==x,,drop=F];return(xmat[1,])}) 
>  > print(newtemp2) #looks like matrix
>    [,1] [,2] [,3] [,4] [,5] [,6]
> A1 1    2    3    4    5    6
> A2 1    2    3    4    5    6
> A3 1    2    3    4    5    6
> A4 1    2    3    4    5    6

The best thing to do in a situation like this is to use the str function 
to see the details of the structure of the object.




More information about the R-help mailing list