Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

data.table

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?

like image 831
imsc Avatar asked Dec 28 '25 19:12

imsc


1 Answers

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
like image 154
Cath Avatar answered Dec 30 '25 15:12

Cath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!