This is my current code (I'm a greenhorn!). Although it does the job, but I'm curious to find a more efficient code.
day1_av <- tapply(day1$lots_available, day1$hour, mean) %>% data.frame()
day2_av <- tapply(day2$lots_available, day2$hour, mean) %>% data.frame()
day3_av <- tapply(day3$lots_available, day3$hour, mean) %>% data.frame()
day4_av <- tapply(day4$lots_available, day4$hour, mean) %>% data.frame()
day5_av <- tapply(day5$lots_available, day5$hour, mean) %>% data.frame()
day6_av <- tapply(day6$lots_available, day6$hour, mean) %>% data.frame()
day7_av <- tapply(day7$lots_available, day7$hour, mean) %>% data.frame()
day_av <- cbind(day1_av, day2_av, day3_av, day4_av, day5_av, day6_av, day7_av)
day_av
Is there a way to make a for-loop and create a data frame day_av out of this in R? I tried this:
day_av <- data.frame()
for(i in c(1:7)){
day[i]_av <- tapply(day[i]$lots_available, day[i]$hour, mean) %>% data.frame()
day_av <- rbind(day_av, day[i]_av)
but the square brackets don't seem to send the message across. Appreciate any help, thank you~
You could put all the dataframe in a list and then use tapply
over them
output <- do.call(cbind, lapply(mget(paste0('day', 1:7)) function(x)
tapply(x$lots_available, x$hour, mean)))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.