Reputation: 681
I'm very new to R and I'm still quite close to the bottom of the very steep learning curve I think. So...
I have a data frame (imported from a .csv file). Contains a number of fields - let's call them Field1, Field2, Field3... Field 10.
The fields are numeric. For each row of data I'd like to calculate the average of the lowest 3 (say) numbers. In other words:
((smallest number) + (second smallest number) + (third smallest number))/3
Also there are some NAs in the data so I'd like the calculation to return NA if there aren't actually three numbers to avarage over (although perhaps R will do this naturally anyway).
Is there a succinct way to do this in R and (better still) to store the result as a new field in the existing data frame?
Grateful for any advice. Thanks. A
Upvotes: 0
Views: 71
Reputation: 1086
data(mtcars)
avg3 <- sapply(mtcars, function(x) mean(head(sort(x[!is.na(x)]), 3)))
avg3
mtcars.avg3 <- rbind(mtcars, avg3)
mtcars.avg3
Upvotes: 0
Reputation: 22
For each row of data I'd like to calculate the average of the lowest 3 (say) numbers.
I think this should achieve what you're asking:
data <- mtcars
data$low.mean <- apply(data, 1, function(x) mean(head(sort(x[!is.na(x)]), n = 3)))
Upvotes: 0