firmo23
firmo23

Reputation: 8404

Add a new column to multiple dataframes using a for loop

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?

Upvotes: 0

Views: 54

Answers (1)

mharinga
mharinga

Reputation: 1780

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))

Upvotes: 1

Related Questions