I had a question regarding the colMeans function. Is there a version of this that will not return an error when it runs into a column of length one? For example
temp<-cbind(c(2,2),c(3,4))
colMeans(temp)
[1] 2.0 3.5
But for this one
temp2<-c(2,2)
colMeans(temp2)
Error in colMeans(temp2) :
'x' must be an array of at least two dimensions
But, if I apply the function mean to each column it properly comes up with the value of 2 and 2.
I wrote a function to do this
testfun<-function(i,x){
mean(x[,i])
}
sapply(1:ncol(x),testfun,x)
which gives the same results as colMeans.
I’ve heard that colMeans is supposed to be much faster than this method. So, is there a version of colMeans that will work when my column is of size 1.
As @Paul points out,
colMeansexpects “an array of two or more dimensions” for itsxargument (from?colMeans). Buttemp2is not an arraytemp2can be made into an array:Perhaps
temp2came from subsetting an array, such asBut this is not an array. To keep it as an array, add
drop = FALSEinside the brackets:Then you can use colMeans on the subsetted array.