Reputation: 1443
I'm having difficulties cycling through a list and apply the same format to the same variable in many data frames:
df1 <- structure(list(datetime = structure(c(1446336120, 1446336180,
1446336240, 1446336300, 1446336360), class = c("POSIXct", "POSIXt"
), tzone = "UTC")), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"), .Names = "datetime")
df2 <- structure(list(datetime = structure(c(1446336120, 1446336180,
1446336240), class = c("POSIXct", "POSIXt"), tzone = "UTC")), row.names = c(NA,
-3L), class = c("tbl_df", "tbl", "data.frame"), .Names = "datetime")
I want to apply the same format to all dataframes:
df1$datetime <- format(df1$datetime, "%m/%d/%Y %H:%M:%S")
df2$datetime <- format(df2$datetime, "%m/%d/%Y %H:%M:%S")
I tried this:
list_df <- mget(ls(pattern = "df"))
lapply(seq_along(list_df),
function(i) format(list_df[[i]]$datetime, "%m/%d/%Y %H:%M:%S"))
but not sure how to assign it back to each dataframe.
Upvotes: 1
Views: 538
Reputation: 522171
I think your current approach is not far off, but you never make an assignment back to the data frame. Add each data frame to a list and then use lapply
:
lst <- list(df1, df2)
lapply(lst, function(x) {
x$datetime <- format(x$datetime, "%m/%d/%Y %H:%M:%S")
return(x)
})
At this point you have a list of data frames in the format you want. If you then later wanted to export each data frame to a CSV file, you could try this:
for (i in 1:length(lst)) {
filename <- paste0("out", i, ".csv")
write.csv(lst[[i]], file=filename)
}
Upvotes: 2
Reputation: 7163
library(dplyr)
lapply(list_df, function(x) x %>%
mutate(datetime=format(datetime, "%m/%d/%Y %H:%M:%S")))
Upvotes: 1