No dimensions of non-empty numeric vector in R

2019-01-27 15:50发布

问题:

I have a problem with my numeric vector and dim() in R. I want to know the dimensions of my vector X with:

dim(X)

However, that function returns NULL.

If I type:

X

I can see that the X is not empty. Why does dim or nrow report it as "NULL"?

Part of X:
[93486] 6.343e-01 6.343e-01 6.343e-01 6.343e-01 6.343e-01 6.343e-01 6.346e-01
[93493] 6.346e-01 6.347e-01 6.347e-01 6.347e-01 6.347e-01 6.347e-01 6.347e-01
[93500] 6.347e-01 6.347e-01 6.347e-01 6.347e-01 6.347e-01 6.347e-01 6.347e-01
[93507] 6.347e-01 6.347e-01 6.347e-01 6.347e-01 6.347e-01 6.347e-01 6.347e-01
[93514] 6.347e-01 6.347e-01 6.347e-01 6.347e-01 6.347e-01 6.347e-01 6.347e-01
[93521] 6.347e-01 6.347e-01 6.347e-01 6.348e-01 6.348e-01 6.348e-01 6.348e-01
[93528] 6.348e-01 6.348e-01 6.348e-01 6.348e-01 6.348e-01 6.348e-01 6.348e-01
[93535] 6.348e-01 6.348e-01 6.348e-01 6.348e-01 6.348e-01 6.348e-01 6.348e-01
[93542] 6.348e-01 6.348e-01 6.348e-01 6.348e-01 6.348e-01 6.348e-01 6.348e-01
[93549] 6.348e-01 6.348e-01 6.348e-01 6.348e-01 6.348e-01 6.348e-01 6.348e-01
[93556] 6.348e-01 6.348e-01 6.349e-01 6.349e-01 6.349e-01 6.349e-01 6.349e-01
[93563] 6.349e-01 6.349e-01 6.349e-01 6.349e-01 6.349e-01 6.349e-01 6.349e-01
[93570] 6.349e-01 6.349e-01 6.349e-01 6.349e-01 6.349e-01 6.349e-01 6.349e-01

> dim(X)
NULL
> class(X)
[1] "numeric"
> nrow(pvals_vector)
NULL

Why is there no dimensions of X?

回答1:

Because it is a one-dimensional vector. It has length. Dimensions are extra attributes applied to a vector to turn it into a matrix or a higher dimensional array:

x <- 1:6
dim( x )
#NULL

length( x )
#[1] 6

dim( matrix( x , 2 , 3 ) )
#[1] 2 3


回答2:

As a side note, I wrote a function which returns length if dim==NULL :

function(items) {

        dims<-vector('list',length(items))
        names(dims)<-items
        for(thing in seq(1,length(items))) {
                if (is.null(dim(get(items[thing])))) {

                        dims[[thing]]<-length(get(items[thing]))
                        } else{
                                #load with dim()
                                dims[[thing]]<-dim(get(items[thing]))
                                }
                }
        return(dims)
        }

Or, as SimonO pointed out, you can "force" a 1xN matrix if desired.



标签: r vector numeric