BrooklynSon
BrooklynSon

Reputation: 2103

How to apply specific columns to sapply function in R?

For example:

sapply(cars[2:3], FUN = IQR)

But how about if I wanted index 2 and 5? Also instead of indexes is there any way to use the column names instead?

Upvotes: 1

Views: 955

Answers (1)

akrun
akrun

Reputation: 886948

We can use anonymous function

sapply(names(cars)[1:2], function(x) IQR(cars[[x]]))

If we wanted columns 2 and 5, use c instead of seq operator (using a different dataset as cars have only two columns)

sapply(mtcars[c(2, 5)], IQR)
#   cyl drat  
# 4.00 0.84 

Upvotes: 1

Related Questions