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
  • 7,287
  • 3
  • 36
  • 66
Angel Cloudwalker
  • 2,015
  • 5
  • 32
  • 54
  • `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
  • 874,273
  • 37
  • 540
  • 662
  • If we pass a vector for example with 2, 5, can we also use the column names? – Angel Cloudwalker Feb 08 '20 at 18:27
  • 1
    @MilesMorales Either you can use numeric index or names. It doesn't make sense to subset the names with a numeric index and then get the columns. i.e. `v1 <- c(2, 5)` we can directly do `sapply(mtcars[v1], IQR)` instead of `sapply(mtcars[names(mtcars)[v1]], IQR)` though both give the same answer – akrun Feb 08 '20 at 18:29
  • 1
    I confirmed this works! sapply(cars[c("price","passengers")], FUN = IQR), appreciate the help! – Angel Cloudwalker Feb 08 '20 at 18:31
  • 1
    Will do! It's just stack overflow makes you wait a few minutes before allowing an answer. Thanks for the speedy resolution! – Angel Cloudwalker Feb 08 '20 at 18:46