简体   繁体   中英

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?

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM