still getting used to purrr and I have one of those questions that I think should be easy, but I don't know how to do it. All I want to do is convert the datetimes in the below, to dates with as.Date(). it's a list of dataframes. Been playing around but haven't found something that works yet... any help appreciated.
df <- data.frame(Date = seq.POSIXt(Sys.time(), Sys.time() + hours(24), by = "hour"),
useless = "ignore me")
df2 <- data.frame(Date = seq.POSIXt(Sys.time(), Sys.time() + hours(1), by = "min"),
useless = "ignore me")
mylist <- list(df,df2)
mylist %<>% map(?????)
You can combine
map()
withmutate()
from the dplyr package (also tidyverse).map()
can be used to applymutate()
each data frame in your list.mutate()
can applyas.Date()
to theDate
column. You'd write it like this:This line is saying:
map()
/apply themutate()
function to each object inmylist
mutate()
is applied to an object, do it as if you were writingmutate(object, Date = as.Date(Date))
Full code:
The canonical way to achieve your goal would be to combine
map
with some verb fromdplyr
, likemutate_at
. Currentlypurrr
still has the functiondmap_at
, but it will be removed frompurrr
in the future.Hence, you would
map
over your list, and then modify the date column withmutate_at
:You could also use
at_depth
, which in the case ofat_depth(1, ...)
is equal tomap
and is therefore not necessary:The original approach, staying within
purrr
, was to usedmap_at
:But since we now have
mutate_at
andmutate_all
and friends, it is recommended to use them instead ofdmap
,dmap_at
and so forth.Data