r Error dim(X) must have a positive length? -
i want compute mean of "population" of built-in matrix state.x77. codes :
apply(state.x77[,"population"],2,fun=mean) #error in apply(state.x77[, "population"], 2, fun = mean) : # dim(x) must have positive length how can prevent error? if use $ sign
apply(state.x77$population,2,mean) # error in state.x77$population : $ operator invalid atomic vectors what atomic vector?
to expand on joran's comments, consider:
> is.vector(state.x77[,"population"]) [1] true > is.matrix(state.x77[,"population"]) [1] false so, population data no diferent other vector, 1:10, has neither columns or rows apply against. series of numbers no more advanced structure or dimension. e.g.
> apply(1:10,2,mean) error in apply(1:10, 2, mean) : dim(x) must have positive length which means can use mean function directly against matrix subset have selected: e.g.:
> mean(1:10) [1] 5.5 > mean(state.x77[,"population"]) [1] 4246.42 to explain 'atomic' vector more, see r faq again (and gets bit complex, hold on hat)...
r has 6 basic (‘atomic’) vector types: logical, integer, real, complex, string (or character) , raw. http://cran.r-project.org/doc/manuals/r-release/r-lang.html#vector-objects
so atomic in instance referring vectors basic building blocks of r objects (like atoms make in real world).
if read r's inline entering ?"$" command, find says:
‘$’ valid recursive objects, , discussed in section below on recursive objects.
since vectors (like 1:10) basic building blocks ("atomic"), no recursive sub-elements, trying use $ access parts of them not work.
since matrix (statex.77) vector dimensions, like:
> str(matrix(1:10,nrow=2)) int [1:2, 1:5] 1 2 3 4 5 6 7 8 9 10 ...you can't use $ access sub-parts.
> state.x77$population error in state.x77$population : $ operator invalid atomic vectors but can access subparts using [ , names so:
> state.x77[,"population"] alabama alaska arizona... 3615 365 2212...
Comments
Post a Comment