Reputation: 849
I have a list of dataframes i want convert in to each column of the dataframe in to time stamp
gg=list(a = data.frame(X1 = c(1516087622, 1516087622, 1516087622, 1516087622,
1516087622), X2 = c(1516087622, 1516087622, 1516087622, 1516087622,
1516087622)),b = data.frame(X1 = c(1516078740, 1516078740, 1516078740, 1516078740,
1516078740), X2 = c(1516078740, 1516078740, 1516078740, 1516078740,
1516078740)))
> gg
$a
X1 X2
1 1516087622 1516087622
2 1516087622 1516087622
3 1516087622 1516087622
4 1516087622 1516087622
5 1516087622 1516087622
$b
X1 X2
1 1516078740 1516078740
2 1516078740 1516078740
3 1516078740 1516078740
4 1516078740 1516078740
5 1516078740 1516078740
I am using the following function
Map(as.POSIXct,lapply(gg,function(x) x[[1]]),origin = "1970-01-01")
it's convert the first column of the each dataframe but i want convert all at a time ..
I need base R function.
Thank you.
Upvotes: 1
Views: 190
Reputation: 887088
Here is one option with tidyverse
. We map
through the list
elements and with mutate_all
change all the columns to POSIXct
class
library(dplyr)
library(purrr)
map(gg, ~ .x %>%
mutate_all(funs(as.POSIXct(., origin = "1970-01-01"))))
#$a
# X1 X2
#1 2018-01-16 12:57:02 2018-01-16 12:57:02
#2 2018-01-16 12:57:02 2018-01-16 12:57:02
#3 2018-01-16 12:57:02 2018-01-16 12:57:02
#4 2018-01-16 12:57:02 2018-01-16 12:57:02
#5 2018-01-16 12:57:02 2018-01-16 12:57:02
#$b
# X1 X2
#1 2018-01-16 10:29:00 2018-01-16 10:29:00
#2 2018-01-16 10:29:00 2018-01-16 10:29:00
#3 2018-01-16 10:29:00 2018-01-16 10:29:00
#4 2018-01-16 10:29:00 2018-01-16 10:29:00
#5 2018-01-16 10:29:00 2018-01-16 10:29:00
The corresponding base R
option would be to loop through the list
elements with Map
, then loop through each column of the dataset with lapply
and assign the transformed value to the dataset (x[] <-
), return the dataset
Map(function(x) {x[] <- lapply(x, as.POSIXct, origin = "1970-01-01");x }, gg)
Upvotes: 1