Search code examples
rtibble

Why the "logical" argument returns different outputs for vectors vs. tibbles


Can someone tell me why the "logical" argument returns different outputs for vectors vs. tibbles:

 a<-c(1,0,"t")
 the_numeric<-vector("logical",length(a))
 for (i in seq_along(a)) the_numeric[[i]] <- is.numeric(a[[i]])
 the_numeric
[1] FALSE FALSE FALSE

 df<-tibble::tibble(
     a=rnorm(10),
     b=rnorm(10),
     c=sample(letters,10)
     )
 the_numeric<-vector("logical",length(df))
 for (i in seq_along(df)) the_numeric[[i]] <- is.numeric(df[[i]])
 the_numeric
[1]  TRUE  TRUE FALSE

Solution

  • The difference is not between vectors vs tibbles but vectors vs lists (tibble/dataframes are special kind of list).

    Vectors can hold data of only one class. Hence, all the values of a become character which is the most common class but that is not the case with dataframes/tibbles where they can hold data of different classes in different columns.

    a<- c(1,0,"t")
    a
    #[1] "1" "0" "t"
    
    class(a)
    #[1] "character"
    
    sapply(df, class)
    #          a           b           c 
    #  "numeric"   "numeric" "character"