简体   繁体   中英

lapply date format to many dataframes

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.

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)
}
library(dplyr)
lapply(list_df, function(x) x %>% 
      mutate(datetime=format(datetime, "%m/%d/%Y %H:%M:%S")))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM