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?
dim() function in R Language is used to get or set the dimension of the specified matrix, array or data frame.
dim() of Array in R To get the dimension of the array in R, use the dim() function.
sapply() function in R Language takes list, vector or data frame as input and gives output in vector or matrix. It is useful for operations on list objects and returns a list object of same length of original set.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With