【问题标题】:Trying to write a for loop in R that adds values to a vector if a condition is satisfied尝试在 R 中编写一个 for 循环,如果满足条件,则将值添加到向量
【发布时间】:2020-03-03 14:32:31
【问题描述】:

我试图定义一个名为 IQR 的向量,它返回另一个向量的内四分位数范围内的值(不是按数字顺序)。

我已经尝试了无数次迭代

IQR <- function(y) for (i in seq_along(y)) { if ((i > quantile(y, 0.25)) && (i < quantile(y, 0.75))) {iqr <- c(i)} else {break}}

IQR <- vector('double', 0) for (i in seq_along(Vect)) {if ((i > quantile(y, 0.25)) && (i < quantile(y, 0.75))) {iqr <- vector(i)} else {break}}

其中 vect 是一个独立向量,包含从 df 创建的要测试的值

【问题讨论】:

  • 请分享更多细节,比如输出是什么

标签: r for-loop if-statement vector


【解决方案1】:

使用提取运算符[] 选择向量中满足条件的元素

类似这样的:

IQR <- function(y)  y[ y>quantile(y,0.25) & y<quantile(y,0.75) ]  
# read as 'y, where y is greater than the 25th centile of y and y is less than the 75th centile of y'

IQR(1:10)
[1] 4 5 6 7

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-12
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 2021-10-20
    • 2019-04-06
    相关资源
    最近更新 更多