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()?