-1

I have a dataset with multiple columns, I want the highest value in the rest of the fields except the date field. I want output like this. enter image description here

Dataset:- https://docs.google.com/spreadsheets/d/1obrS4IwqedkIZ1puvY1Coxrl9K63YEb2D_2jgsXSKHM/edit

  • 1
    Hi Aashu. It would be easier to help you if you provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including the code you have tried and a snippet of your data or some fake data. Please do not post an image of code/data/errors [for these reasons](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question/285557#285557). Just include your data directly using e.g. the `dput()` function. – stefan Nov 05 '22 at 07:50

1 Answers1

0

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

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66