我如何有条件地应用which.min函数

时间:2018-11-15 12:37:54

标签: r

我想在数据框中创建一列,并在满足条件的列中的数据框中填充最小值:

**Sample data** 
Variable value
A         10
A         20
A         30
B         5
B         60
B         70

预期结果:

Variable value   NewColumn
A         10     min
A         20     between min to 20
A         30     between 21 to 30
B         5      min
B         60     between 50 to 60

有没有简单的方法可以实现这一目标?

1 个答案:

答案 0 :(得分:1)

问题中的输出似乎不一致,因为有时下限比上限少10,而其他时候则少9。我们已将其定义为小于9,并且如果min为上限以下9或10,则写<!DOCTYPE html> <html> <body> <form action=""> <input type="radio" name="gender" value="male"> Male<br> <input type="radio" name="gender" value="female"> Female<br> <input type="radio" name="gender" value="other"> Other </form> <p><b>Note:</b> When a user clicks on a radio-button, it becomes checked, and all other radio-buttons with equal name become unchecked.</p> </body> </html> 而不是下限。

现在,定义一个函数,该函数输入向量min并使用x对其进行分类,以将其分别应用于每个组。不使用任何软件包。

ave

给予:

categorize <- function(x) {
  upper <- 10 * ceiling(x / 10)
  lower <- ifelse(upper-9 == min(x) | upper-10 == min(x), "min", upper-9)
  ifelse(x == min(x), "min", paste("between", lower, "to", upper))
}

transform(DF, New = ave(value, Variable, FUN = categorize))

注意

使用的输入 Variable value New 1 A 10 min 2 A 20 between min to 20 3 A 30 between 21 to 30 4 B 5 min 5 B 60 between 51 to 60 6 B 70 between 61 to 70 以可重复的形式是:

DF