Wet Feet
Wet Feet

Reputation: 4555

R: Using function `max` in `by`

Newbie question here, but I am trying to use by on a dataframe named x2. x2$second is numeric, but somehow I am still receiving this error.

x2<-data.frame(first=c("a","a","a","b","b","b"),second=c(1,2,NA,1,3,5))
x2
#  first second
#1     a      1
#2     a      2
#3     a     NA
#4     b      1
#5     b      3
#6     b      5
by(x2,x2$first,max,na.rm=TRUE)
#Error in FUN(X[[1L]], ...) : 
#  only defined on a data frame with all numeric variables

Upvotes: 0

Views: 92

Answers (1)

Marius
Marius

Reputation: 60070

The first argument should only contain the data you want to apply max to, not your whole dataframe. Here, you only want to apply it to the second column:

by(x2$second, x2$first, max, na.rm=TRUE)

Output:

x2$first: a
[1] 2
------------------------------------------------------------------------------------------- 
x2$first: b
[1] 5

Upvotes: 1

Related Questions