I'm trying to implement a function that given a data frame returns the same data frame with four columns added. These new four columns are: for each row, I get the maximun element and its index and put them as two new columns. I do the same with the second maximum element. Don't care if they are repeated. This is my code for this task:
add_2max <- function(x)
{
max1 = max(x, na.rm=TRUE)
indmax1 = which.max(x)
y=x[-c(indmax1)]
max2 = max(y, na.rm=TRUE)
indmax2 = which(x==max2)
indmax2 = ifelse(max1==max2, indmax2[2], indmax2[1])
x=c(x, max1, max2, indmax1, indmax2)
return (x)
}
add_2max_df <- function(DF)
{
NewDF=t(apply(DF, 1, add_2max))
return(NewDF)
}
I'm sure this code can be improved! What do you recommend in order to do that? Is it fast enough?
Many thanks in advance Regards!
ifelseis notoriously slow, but since its working on a single row it shouldn't be an issue. As far as you last question... is it fast enough for you? – Justin Apr 11 '12 at 15:41which.max(x,nth_biggest)function. – Carl Witthoft Apr 11 '12 at 16:39