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

后端 未结 1 498
庸人自扰
庸人自扰 2020-12-09 15:13

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          


        
相关标签:
1条回答
  • 2020-12-09 15:46

    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...
    
    0 讨论(0)
提交回复
热议问题