Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. E.g.

> 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: E.g.:

> 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...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...