Why is "vector" considered a "list" in some cases?

Asked

Viewed 100 times

6

Consider the objects:

 for(i in 1:6){
  names<-paste0("var",i)
  assign(names,runif(30,20,100))
 }

dataset<-do.call(
  cbind.data.frame,
  mget(ls(pattern='*v'))
)

cluster<-kmeans(dataset,centers=3)
dataset$kmeans<-as.factor(cluster[['cluster']])

mylist<-split(dataset,dataset$kmeans)
 names(mylist)<-paste('dataset',seq_along(mylist),sep='')

I tried to eliminate ONLY the vectors of globalenv():

rm(list=ls(Filter(is.vector,mget(ls()))))

But, the objects dataset (one data.frame) and cluster (one list) remain in the globalenv(). However, mylist and the vectorwere eliminated.

I ask you:

  • why mylist was eliminated and cluster remained (both have typeof list)?
  • why a class object list was eliminated, as occurred with mylist (I specified vector as an argument)?
  • 1

    You won’t be able to write an answer now. But the tip is here. Lists are a generic vector. The other vectors are atomic vectors.

  • 1

    The function is.vector() has an argument mode that can receive the typeof(x) basic or "list" or "Expression" or "any". See ?is.vector.

  • But why the object cluster (one list) still remains. He possesses the same typeof of mylist (i and.., list) and this is eliminated.

1 answer

3


The attribute that cluster inheritance is not list but yes kmeans. is.vector must look for the class attribute of an object (if you have it), see this example:

baz <- c(1:10)
is.vector(baz) # TRUE
class(baz) <- "brasil"
is.vector(baz) # FALSE
class(baz) <- "integer"
is.vector(baz) # TRUE
class(baz) <- "list"
is.vector(baz) # TRUE

On the console ?typeof:

Description

typeof determines the (R Internal) type or Storage mode of any Object

Therefore, typeof does not look at the attribute and, yes, the "type or storage mode". And the is.vector look at the attribute (?is.vector):

...

is.vector Returns TRUE if x is a vector of the specified mode having no Attributes other than Names. It Returns FALSE otherwise.

...

If mode = "any", is.vector may Return TRUE for the Atomic modes, list and Expression. For any mode, it will Return FALSE if x has any Attributes except Names.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.