I have a numeric matrix and I want to get the mean of the 5 lowest (smallest value) elements from each column. I am trying to use one of the different apply functions available. But I am not able to do it.
This is the function I need to apply, and I have tested it with a for loop, and works great.
mean(head(sort(table[,x]),5))
This is one of the several examples I have tried to:
a<-mapply(function(x){mean(head(sort(table[,x]),5))},table)
I get the following error:
Error in `[.data.frame`(x, order(x, na.last = na.last, decreasing = decreasing)) : undefined columns selected
I have also tried sapply, lapply... but I haven't make it work. Can't find anything to base on, surfing the internet..
Thanks in advance
apply(df, 2, function(x) mean(sort(x, decreasing = F)[1:5]))
– mts