Basic for() loop in R

前端 未结 1 1264
猫巷女王i
猫巷女王i 2021-01-28 11:13

I\'m new to loops and R in general. Using the \"iris\" datasets I need to use a for() loop and create an object called \'X.IQR\' that contains the interquartile range of each o

1条回答
  •  清酒与你
    2021-01-28 11:37

    When selecting a subset of the data if you intend to have all the rows, as you have, you can just omit the row selection:

    iris[1:150,1:4]
    

    becomes

    iris[ ,1:4]
    

    as Richard mentioned in a comment, you can use sapply:

    X.IQR = sapply(X = iris[,1:4], FUN = IQR)
    

    sapply will apply the FUN (function) IQR to each element of the iris dataset, which corresponds to its columns.

    or using apply:

    X.IQR = apply(X = iris[ ,1:4], 2, FUN = IQR)
    

    apply can do the same thing, but its a bit more code and won't always be as clean.

    Read more with the excellent response here: R Grouping functions: sapply vs. lapply vs. apply. vs. tapply vs. by vs. aggregate

    0 讨论(0)
提交回复
热议问题