R:pick the max one out of each colomn

Viewed 32
a=c(1,4,5,7,3,3,NA)
b=c(2,7,3,NA,2,5,2)
d=c(2,7,5,NA,9,0,1)
dat=data.frame(a,b,d)

How to pick the max one out of each colomn and the NA are neglected? Finally the result is a vector which concludes 7,7 and 9.What is the code to obtain such a result?

3 Answers

Use sapply to iterate over columns.

sapply(dat, max, na.rm = TRUE)
# a b d
# 7 7 9

Alternatively, if you use lapply it will return a list. sapply can be a little unpredictable, in that it calls lapply and then tries to simplify the result. This means that if the input type changes (e.g. one of the columns is a list column), you may get a different output, (e.g. a list rather than a vector).

If you want to ensure that the output is a vector and throw an error if this is not the case you can use vapply:

vapply(
    X = dat, 
    FUN = max, 
    FUN.VALUE = numeric(1), 
    na.rm = TRUE
)
# a b d
# 7 7 9
a=c(1,4,5,7,3,3,NA)
b=c(2,7,3,NA,2,5,2)
d=c(2,7,5,NA,9,0,1)
dat=data.frame(a,b,d)
sapply(dat, max, na.rm=TRUE)
a b d 
7 7 9 

Using apply:

apply(dat, 2, max, na.rm = 1)
a b d 
7 7 9 
Related