0

I have the dataframe below:

library lubridate

eventtime<-c("2020-02-07 22:06:00","2020-02-07 22:00:00","2020-02-07 21:46:00")
eventvalue<-c("home","work",'exit')
geof<-data.frame(eventtime,eventvalue)

Then I use a list to store them and assign the list elements to different data.frames using:

library(lubridate)
library(tidyverse)

list1 <- geof %>%
  split(.$eventvalue) %>%
  bind_rows() %>%
  mutate(EventHour = hour(eventtime)) %>%
  split(.$eventvalue)

for (i in names(list1)) setNames(assign(i, data.frame(list1[[i]])), names(list1))

I would like then to use table() based on EventHour for each dataframe to create new dataframes with the frequency of each EventHour and then rename those columns

#table the events by count of hours
tablegeh<-data.frame(table(home$EventHour))

colnames(tablegeh)<-c("Hour","Frequency")

1 Answer 1

2

You can use lapply:

lapply(list1, function(x) table(x$EventHour))
#> $exit
#> 21 
#>  1 
#>
#> $home
#> 22 
#>  1 
#>
#> $work
#> 22 
#>  1 

Obviously, you only have a single entry in each data frame, so the "tables" don't look much like tables!

Sign up to request clarification or add additional context in comments.

4 Comments

how can I save those new dataframes and rename their columns as well?yes they re just examples
@firmo23 you can choose whichever names you want if you do, for example, lapply(list1, function(x) setNames(as.data.frame(table(x$EventHour)), c("Hour", "n"))). If you want to save them, you can save the whole list as an RDS, or convert them all into one big data frame using do.call(rbind, list1), or save each one to csv using mapply(function(x) write.csv(x, y), list1, c("exit.csv", "home.csv", "work.csv"))
thank you but I do not mean to save them in a file but as separated dataframes for later use
@firmo23 if you do list2 <- lapply(list1, function(x) table(x$EventHour)) then you can access each one by e.g. list2$home, which gives you the whole home data frame. If you like you can store a copy outside the list with home <- list2$home

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.