简体   繁体   中英

r Error dim(X) must have a positive length?

I want to compute the mean of "Population" of built-in matrix state.x77 . The codes are :

apply(state.x77[,"Population"],2,FUN=mean)

#Error in apply(state.x77[, "Population"], 2, FUN = mean) : 

# dim(X) must have a positive length

how can I prevent this error? If I use $ sign

apply(state.x77$Population,2,mean)
# Error in state.x77$Population : $ operator is invalid for atomic vectors

What is atomic vector?

To expand on joran's comments, consider:

> is.vector(state.x77[,"Population"])
[1] TRUE
> is.matrix(state.x77[,"Population"])
[1] FALSE

So, your Population data is now no diferent from any other vector, like 1:10 , which has neither columns or rows to apply against. It is just a series of numbers with no more advanced structure or dimension. Eg

> apply(1:10,2,mean)
Error in apply(1:10, 2, mean) : dim(X) must have a positive length

Which means you can just use the mean function directly against the matrix subset which you have selected: Eg:

> mean(1:10)
[1] 5.5
> mean(state.x77[,"Population"])
[1] 4246.42

To explain 'atomic' vector more, see the R FAQ again (and this gets a bit complex, so hold on to your hat)...

R has six basic ('atomic') vector types: logical, integer, real, complex, string (or character) and raw. http://cran.r-project.org/doc/manuals/r-release/R-lang.html#Vector-objects

So atomic in this instance is referring to vectors as the basic building blocks of R objects (like atoms make up everything in the real world).

If you read R's inline help by entering ?"$" as a command, you will find it says:

'$' is only valid for recursive objects, and is only discussed in the section below on recursive objects.

Since vectors (like 1:10 ) are basic building blocks ("atomic"), with no recursive sub-elements, trying to use $ to access parts of them will not work.

Since your matrix ( statex.77 ) is essentially just a vector with some dimensions, like:

> str(matrix(1:10,nrow=2))
 int [1:2, 1:5] 1 2 3 4 5 6 7 8 9 10

...you also can't use $ to access sub-parts.

> state.x77$Population
Error in state.x77$Population : $ operator is invalid for atomic vectors

But you can access subparts using [ and names like so:

> state.x77[,"Population"]
   Alabama         Alaska        Arizona...
      3615            365           2212...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM