[R] Calculating "row standard deviations"

David Winsemius dwinsemius at comcast.net
Tue Jun 23 02:00:20 CEST 2009


On Jun 22, 2009, at 6:19 PM, Mark Na wrote:

> Hi R-helpers,
>
> I have been struggling with calculating row and column statistics,
> e.g. standard deviation.
>
> I know that
>> datac$Mean<-rowMeans(datac,na.rm=TRUE)
> will give me row means.
>
> I have tried to replicate those row means with the apply function:
>> datac$Mean2<-apply(datac,2,mean)
>
> so that I can replace the function argument with "sd" (instead of
> mean) to get standard deviations.
>
> But, I'm running into this error:
>
>> dim(datac)
> [1]  17 271
>> datac$Mean2<-apply(datac,2,mean)
> Error in dimnames(x) <- dn :
>  length of 'dimnames' [2] not equal to array extent

If you are trying to create a group means value for each element in an  
array or data.frame then the function to use is ave with its default  
function is mean. Other functions can be used but that is not  
necessary here. You could try:

datac$Mean2<-apply(datac,2,ave)


>
>
> Can anyone see what I'm doing wrong?
>
> Thanks!
>
> Mark Na

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list