Here is a way with a built-in data set, mtcars
. I will first create a "Date"
column.
Determine which columns are numeric, then sapply
function max
to those columns.
df1 <- mtcars
df1$date <- Sys.Date()
df1 <- df1[c(ncol(df1), 1:(ncol(df1) - 1L))]
i <- sapply(df1, is.numeric)
sapply(df1[i], max, na.rm = TRUE)
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> 33.900 8.000 472.000 335.000 4.930 5.424 22.900 1.000 1.000 5.000 8.000
Created on 2022-11-05 with reprex v2.0.2
Edit
If there are columns with all values NA
, the code above will not process them. If even those columns are needed, try instead
df1 <- mtcars
df1$date <- seq(Sys.Date(), by = "days", length.out = nrow(df1))
df1 <- df1[c(ncol(df1), 1:(ncol(df1) - 1L))]
df1$All_na <- NA
i <- sapply(df1, is.numeric)
j <- sapply(df1, is.logical)
sapply(df1[i | j], \(x) if(all(is.na(x))) NA else max(x, na.rm = TRUE))
#> mpg cyl disp hp drat wt qsec vs am gear carb All_na
#> 33.900 8.000 472.000 335.000 4.930 5.424 22.900 1.000 1.000 5.000 8.000 NA
Created on 2022-11-05 with reprex v2.0.2