R max function ignores NA

I have a working code. When I copy the same things in a different dataset, I get errors :(

#max by values
df <- data.frame(age=c(5,NA,9), marks=c(1,2,7), story=c(2,9,NA))
df

df$colMax <- apply(df[,1:3], 1, function(x) max(x[x != 9],na.rm=TRUE))
df

I tried to do the same on larger data, and I get warnings, why?

maindata$max_pc_age <- apply(maindata[,c(paste("Q2",1:18,sep="_"))], 1, function(x) max(x[x != 9],na.rm=TRUE))


50: In max(x[x != 9], na.rm = TRUE) :
  no non-missing arguments to max; returning -Inf

to better understand the problem, I made the changes as shown below, but still get warnings

maindata$max_pc_age <- apply(maindata[,c(paste("Q2",1:18,sep="_"))], 1, function(x) max(x,na.rm=TRUE))
1: In max(x, na.rm = TRUE) : no non-missing arguments to max; returning -Inf
+4
source share
2 answers

, . NA s, -Inf, , . , ( , -Inf , ). ,

 my.max <- function(x) ifelse( !all(is.na(x)), max(x, na.rm=T), NA)

. (all) x NA, NA, max . - , NA . apply -. .

 maindata$max_pc_age <- apply(maindata[,c(paste("Q2",1:18,sep="_"))], 1, my.max)

R NA . , test <- NA; test==NA, NA ( TRUE, is.na(test))), , , , , , ? , , max -Inf, , , , . , , , NA .

+8

:

df[2,2] <- NA
df[1,2] <- -5

apply(df, 1, function(x) max(x[x != 9],na.rm=TRUE))
#[1]    5 -Inf    7
#Warning message:
#In max(x[x != 9], na.rm = TRUE) :
#  no non-missing arguments to max; returning -Inf

:

df1 <- df  
minVal <- min(df1[!is.na(df1)])-1

df1[is.na(df1)|df1==9] <- minVal
val <- do.call(`pmax`, df1)
val[val==minVal] <- NA
val
#[1]  5 NA  7
+1

Source: https://habr.com/ru/post/1546752/


All Articles