简体   繁体   中英

R to return max and min dates for list of dataframes

I used the following code to get the max and min dates of the "dates" column of 3 different dataframes. I do not receive any output in my console? Did I do it correctly, or do I need to create a separate function and use lapply?

df2 <- list(daily_activity,
+             hourly_activity,
+             sleep_day)
> for (i in 1:length(df2)){
+   max_date <- max(df2[[i]]$date)
+   min_date <- min(df2[[i]]$date)
+   return(c(max_date,min_date))
+ }

We may use lapply on the list

lapply(df2, function(x) c(max(x$date, na.rm = TRUE), 
      min(x$date, na.rm = TRUE)))

1) Using the reproducible inputs in the Note at the end this gives a tibble whose first row is the minima and second row is the maxima.

library(purrr)

map_df(L, ~ range(.$date))
## # A tibble: 2 × 3
##   a          b          c         
##   <date>     <date>     <date>    
## 1 1970-01-01 1970-01-01 1970-01-01
## 2 1970-01-04 1970-01-04 1970-01-04

2) If you want to specifically just fix up the code in the question using for then iterate over the names and use cat to display the output.

for (nm in names(L)) {
   d <- L[[nm]]$date
   max_date <- max(d)
   min_date <- min(d)
   cat(nm, format(max_date), format(min_date), "\n")
}
## a 1970-01-04 1970-01-01 
## b 1970-01-04 1970-01-01 
## c 1970-01-04 1970-01-01 

or shorter:

for (nm in names(L)) cat(nm, format(range(L[[nm]]$date)), "\n")

Note

DF <- data.frame(date = .Date(0:3), v = 0:3)
L <- list(a = DF, b = DF, c = DF)

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