No dimensions of non-empty numeric vector in R

给你一囗甜甜゛ 提交于 2019-11-29 13:37:20

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

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

edit June 2019:

I rewrote this function so it doesn't foul up calls to base::dim inside any existing functions.

# return dim() when it's sensible and length() elsewise
#  let's not allow multiple inputs, just like base::dim, base::length
# Interesting fact --  the function  "dim" and the function  " dim<-" are different
# primitives, so this function here doesn't interfere with the latter.
dim <- function(item) {
        if (is.null(base::dim(item)) ) { 
            dims<-length(item)  
            } else{
                dims  <- base::dim(item)  
                }
    return(dims)
    }

Below is the original posted code

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!