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 gather all its unique eventvalue values to a new one.

geoun<-data.frame(unique(geof$eventvalue))

I create new dataframes one for each unique eventvalue

#Create dataframes according to eventvalue
for(i in 1:nrow(geoun)){
  assign(paste0(geoun[i,1]), data.frame(geof[ which(geof$eventvalue==geoun[i,1]), ]))

}

Then I want to repeat the process below-adding a new column- for each one using a for loop.

#extract just the hour maker, so we can count by hour
home$EventHour <- hour(home$eventtime)

I use:

#Create dataframes according to eventvalue
for(i in 1:nrow(geoun)){
  assign(paste0(geoun[i,1]), data.frame(geof[ which(geof$eventvalue==geoun[i,1]), ])$EventHour)<- hour(assign(paste0(geoun[i,1]), data.frame(geof[ which(geof$eventvalue==geoun[i,1]), ]))$eventtime)

}

but I get:

Error in assign(paste0(geoun[i, 1]), data.frame(geof[which(geof$eventvalue ==  : 
  could not find function "assign<-"

How can I achieve that. What is my mistake?

1 Answer 1

1

Easier would be to use a list instead of assigning different data.frames. I think something like this will give the same answer:

library(lubridate)
library(tidyverse)

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

Edit:

You can assign the list elements to different data.frames using:

for (i in names(list1)) setNames(assign(i, data.frame(list1[[i]])), names(list1))
Sign up to request clarification or add additional context in comments.

1 Comment

how can I save each one of the 3 dataframes produced?

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.