1

I'm working through some exercises (Ch.21.2.1, question 1-2) in the book R for Data Science. https://r4ds.had.co.nz/iteration.html

The question is: Determine the type of each column in nycflights13::flights

Here's the code.

library(nycflights13)

output_air <- vector("list", ncol(flights))
names(output_air) = names(flights)

for (i in names(output_air)) {
  output_air[i] = class(flights[[i]])
  print(output_air)
}
output_air #1 with output_air[i]

for (i in names(output_air)) {
  output_air[[i]] = class(flights[[i]])
  print(output_air)
}
output_air #2 with output_air[[i]]

So apparently #2 is the correct way to do it and #1 show the error: "In output_air[i] <- class(flights[[i]]) : number of items to replace is not a multiple of replacement length" but I have no idea why.

The problem here is that when I do #1, the class stored under $time_hour includes only "POSIXct" instead of both "POSIXct" and "POSIXt".

$time_hour
[1] "POSIXct"

$time_hour
[1] "POSIXct" "POSIXt" 
Sam Min
  • 77
  • 5
  • 1
    Since this is for study purposes, do you only need a for-loop answer? – NelsonGon Mar 12 '19 at 14:41
  • 1
    yup anything that will clarify this will be good! – Sam Min Mar 12 '19 at 14:42
  • Take a look here https://stackoverflow.com/questions/1169456/the-difference-between-bracket-and-double-bracket-for-accessing-the-elem. There the difference in referencing list elements with [i] and [[i]] is discussed. Which will answer your question regarding the difference between option #1 and #2. – ha-pu Mar 12 '19 at 15:04
  • Thanks for your help. However, I'm still not sure why [i] allows only one class whereas [[i]] allows both classes to be stored... – Sam Min Mar 12 '19 at 16:19

0 Answers0