imsc
imsc

Reputation: 7840

Maximum value of one data.table column based on other columns

I have a R data.table

DT = data.table(x=rep(c("b","a",NA_character_),each=3), y=rep(c('A', NA_character_, 'C'), each=3), z=c(NA_character_), v=1:9) 
DT
#    x  y  z v
#1:  b  A NA 1
#2:  b  A NA 2
#3:  b  A NA 3
#4:  a NA NA 4
#5:  a NA NA 5
#6:  a NA NA 6
#7: NA  C NA 7
#8: NA  C NA 8
#9: NA  C NA 9

For each column if the value is not NA, I want to extract the max value from column v. I am using

sapply(DT, function(x) { ifelse(all(is.na(x)), NA_integer_, max(DT[['v']][!is.na(x)])) })
 #x  y  z  v 
 #6  9 NA  9

Is there a simpler way to achive this?

Upvotes: 3

Views: 182

Answers (2)

akrun
akrun

Reputation: 886948

We can use summarise_each from dplyr

library(dplyr)
DT %>%
   summarise_each(funs(max(v[!is.na(.)])))
#    x y    z v
#1: 6 9 -Inf 9

Upvotes: 1

Cath
Cath

Reputation: 24074

here is a way, giving you -Inf (and a warning) if all values of the column are NA (you can later replace that by NA if you prefer):

DT[, lapply(.SD, function(x) max(v[!is.na(x)]))]
#    x y    z v
# 1: 6 9 -Inf 9

As suggested by @DavidArenburg, to ensure that everything goes well even when all values are NA (no warning and directly NA as result), you can do:

DT[, lapply(.SD, function(x) {
  temp <- v[!is.na(x)] 
  if(!length(temp)) NA else max(temp)
})]
#   x y  z v
#1: 6 9 NA 9

Upvotes: 3

Related Questions