R中的基本for()循环 [英] Basic for() loop in R

查看:64
本文介绍了R中的基本for()循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般来说,我是循环和R的新手.使用"iris"数据集,我需要使用for()循环并创建一个名为"X.IQR"的对象,其中包含"iris"的前四列中每列的四分位数范围.有人可以在这里为我提供一些见解吗?谢谢!

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!

对不起,忘记了我的尝试

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])
}
}

我在这里尝试过此代码,部分是我的知识,部分是我在课堂上学到的示例代码.我知道这是一个循环,我想我已经指定了前4列,只是我不确定如何在此处合并IQR,有人建议吗?

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?

推荐答案

在选择数据的子集时,如果您希望拥有所有行,则可以忽略行选择:

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]

成为

iris[ ,1:4]

正如Richard在评论中提到的那样,您可以使用sapply:

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

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

sapply 会将 FUN (功能) IQR 应用于虹膜数据集的每个元素,该元素对应于其列.

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

或使用套用:

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

apply 可以做同样的事情,但是它的代码更多,而且并不总是那么干净.

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

这篇关于R中的基本for()循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆