0

I have a list called result2 that contains 366 dataframes and I want to subset each dataframe by the variable names ("time","summary","precipProbability","apparentTemperature","humidity","windSpeed"). I have been able to subset them individually (below) however whenever I have tried to use a for loop or the apply family of functions I have failed.

result2[[1]] <- data.frame(result2[[1]])[, c("time","summary","precipProbability","apparentTemperature","humidity","windSpeed")]
result2[[2]] <- data.frame(result2[[2]])[, c("time","summary","precipProbability","apparentTemperature","humidity","windSpeed")]

Here are my attempts at a for loop which runs but my code gets an error and the errors says that the number of items to replace is not a multiple of replacement length

weather_variables <- c("time","summary","precipProbability","apparentTemperature","humidity","windSpeed")
for (i in 1:366){
      result2[[i]] <- data.frame(result2[[i]])[, weather_variables]
}

Thanks !

  • 1
    Did you mean `for (i in 1:366)`? As written, you're only changing the last one. – MrFlick Dec 09 '20 at 08:47
  • Hey yeah sorry I typed it into StackOverflow wrong! I have edited it now! You were correct – Dylan Johnson Dec 09 '20 at 08:50
  • 1
    Then maybe you typed something else wrong. `result2 <- list(mtcars, mtcars); cols <- c("hp","mpg"); for(i in 1:2) result2[[i]] <- mtcars[, cols]` works just fine for me. It's hard to help further without some sort of [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – MrFlick Dec 09 '20 at 08:52
  • Don't see anything wrong with your code. What is `length(result2)` ? Try `result3 <- lapply(result2, \`[\`, weather_variables)` – Ronak Shah Dec 09 '20 at 08:53
  • @RonakShah Cheers man you smashed it ! Will buy you a coffee for your help ! – Dylan Johnson Dec 09 '20 at 08:57
  • That doesn't make sense. The loop should do the same thing as `lapply`. You must be leaving out an important detail. – MrFlick Dec 09 '20 at 09:08

0 Answers0