No dimensions of non-empty numeric vector in R
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.
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