Skip to content
Prev 359901 / 398503 Next

Using a function with apply Error: undefined columns selected

Hi John,
First, apply isn't guaranteed to work on data frames. There are two
easy ways to do something like this, but we had better have a data
frame:

guppy<-data.frame(taste=rnorm(10,5),
 crunch=rnorm(10,5),satiety=rnorm(10,5))

If you just want to apply a function to all or a subset of columns of
a data frame, a for loop can be used:

fract2.1<-function(col,data) {
 p<-sum(data[,col],na.rm=TRUE)/sum(!is.na(data[,col]))
 return(p)
}
for(col in 1:ncol(guppy)) print(fract2.1(col,guppy))

If you really do want to use an "*apply" function, then the function
has to be written for each column, not the entire data frame:

fract2.2<-function(x) return(sum(x,na.rm=TRUE)/sum(!is.na(x)))
sapply(guppy,fract2.2)

and if you want a subset of the columns, you will have to do it before
you let sapply get into it.

Jim
On Fri, Apr 8, 2016 at 8:39 AM, John Sorkin <jsorkin at grecc.umaryland.edu> wrote: