[R] tapply help
Mark Ebbert
Mark.Ebbert at hci.utah.edu
Fri Jun 4 22:02:01 CEST 2010
Dear R gurus,
I am trying perform what I believe will be a pretty simple task, but I'm struggling to figure out how to do it. I have two vectors of the same length, the first is numeric and the second is factor. I understand that tapply is perfect for applying a function to the numeric vector by subsets of the factors in the second vector. My issue is trying to make use of two other vectors within the custom function I've written for tapply. The two other vectors are a high and low value for each subset I am breaking my data into, and I want to calculate the percentage of data points that fall into each respective range. I will attempt to provide a coherent example:
# create range for each possible class
lows<-c(1,2,3,4,5)
highs<-c(5,6,7,8,9)
# data values
vals<-sample(1:10,100,replace=T)
#classes
classes<-sample(letters[1:5],100,replace=T)
# Try to calculate percentage of values that fall
# into the respective range for the given class.
percentages<-tapply(vals,classes,
function(i){
length(i[i>=lows[index] & i<=highs[index]])/length(i) # I don't know how to actually keep an index count in tapply, but I'm guessing there's a better way.
})
I really appreciate any help.
ME
More information about the R-help
mailing list