Wolfpack
Wolfpack

Reputation: 59

Basic for() loop in R

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 of the first four columns of "iris". Could someone please provide a little insight for me here? Thank you!

Edit: Sorry forgot to include my attempts

for(row in 1:150){
for(column in 1:4){
print(paste("row =",row,"; col =",column))
print(iris[1:150,1:4])
}
}

I've tried this code here which is partially my knowledge and partially example code that I have learned in my class. I understand that this is a loop and I THINK that I have specified the first 4 columns as I desire I'm just not sure how to incorporate IQR here, anyone have any advice?

Upvotes: 0

Views: 473

Answers (1)

zacdav
zacdav

Reputation: 4671

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

Upvotes: 3

Related Questions