1

I wrote a function that I thought determines the type data in each column of the mtcars dataset.

column_type <- vector("character", ncol(nycflights13::flights))
for(i in seq_along(nycflights13::flights)){
  column_type[[i]] <- typeof(nycflights13::flights[[i]])
}
column_type

IT yields the following

> column_type
 [1] "integer"   "integer"   "integer"   "integer"   "integer"   "double"   
 [7] "integer"   "integer"   "double"    "character" "integer"   "character"
[13] "character" "character" "double"    "double"    "double"    "double"   
[19] "double"

But in the book I am using , the solution is instead written with the function class() used instead of typeof. The results are slightly different.

output <- vector("list", ncol(nycflights13::flights))
names(output) <- names(nycflights13::flights)
for (i in names(nycflights13::flights)) {
  output[[i]] <- class(nycflights13::flights[[i]])
}
output
#> $year
#> [1] "integer"
#> 
#> $month
#> [1] "integer"
#> 
#> $day
#> [1] "integer"
#> 
#> $dep_time
#> [1] "integer"
#> 
#> $sched_dep_time
#> [1] "integer"
#> 
#> $dep_delay
#> [1] "numeric"
#> 
#> $arr_time
#> [1] "integer"
#> 
#> $sched_arr_time
#> [1] "integer"
#> 
#> $arr_delay
#> [1] "numeric"
#> 
#> $carrier
#> [1] "character"
#> 

I understand typeof() gives you the type of primitive vector (so it does NOT include dataframe, tibbles, factors, or date, or date-times).

and class() gives you the class, which is another way of describing or designating objects? so its another attribute?

my question is, which solution is more correct and why? and when do you use class vs the vector type (found by using typeof()?

Kevin Lee
  • 321
  • 2
  • 8
  • 4
    Related: [Mode, Class and Type of R objects](https://stats.stackexchange.com/questions/3212/mode-class-and-type-of-r-objects), [Types and classes of variables](https://stackoverflow.com/questions/6258004/types-and-classes-of-variables), [A comprehensive survey of the types of things in R; 'mode' and 'class' and 'typeof' are insufficient](https://stackoverflow.com/questions/8855589/a-comprehensive-survey-of-the-types-of-things-in-r-mode-and-class-and-type) – Henrik Jun 16 '20 at 16:57
  • 1
    *"which solution is more correct"* is completely subjective and contextual. I don't think you'll find a conclusive answer, KevinLee, because of all of their uses. If you only care about differences between `double` and `integer`, then `typeof` works (and it's always length 1!); if you need so know the difference between `list` and `data.frame`, then `class` or `inherits(...)` are what you need. – r2evans Jun 16 '20 at 16:58

0 Answers0