1

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?

Phil
  • 5,491
  • 3
  • 26
  • 61
Angel Cloudwalker
  • 1,903
  • 5
  • 25
  • 52
  • `cars` datasets have only two columns – akrun Feb 08 '20 at 18:24
  • Does this answer your question? [R Apply() function on specific dataframe columns](https://stackoverflow.com/questions/18503177/r-apply-function-on-specific-dataframe-columns) – camille Feb 08 '20 at 18:43
  • Also dplyr examples [here](https://stackoverflow.com/q/21644848/5325862) (`summarise_at`), a few [here](https://stackoverflow.com/q/21295936/5325862) and [here](https://stackoverflow.com/q/43620936/5325862) that should help – camille Feb 08 '20 at 18:52

1 Answers1

1

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 
akrun
  • 789,025
  • 32
  • 460
  • 575