在数据帧的所有子集上应用函数

Jon*_*ein 3 r subset apply

我怎样才能使物种的Sepal.Length值正常化?

    iris
    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
1            5.1         3.5          1.4         0.2     setosa
...

# i have to divide by 
tapply(iris$Sepal.Length, iris$Species, max)
    setosa versicolor  virginica 
       5.8        7.0        7.9 
Run Code Online (Sandbox Code Playgroud)

换句话说,我想将所有值Species=="setosa"除以5.8,依此类推,最后我希望在Sepal.Length列中有一个标准化值为0..1的数据框.

最后应该回归

    iris
    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
1      0.8793103         3.5          1.4         0.2     setosa
...
Run Code Online (Sandbox Code Playgroud)

Jos*_*ien 7

显然,有很多方法可以做到这一点.我喜欢ave()(请参阅DWin的答案)或data.table最佳包的语法:

library(data.table)
dt <- data.table(iris)
dt[, Sepal.Length:=(Sepal.Length)/max(Sepal.Length), by="Species"]
dt
#      Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
#   1:    0.8793103         3.5          1.4         0.2    setosa
#   2:    0.8448276         3.0          1.4         0.2    setosa
#   3:    0.8103448         3.2          1.3         0.2    setosa
#   4:    0.7931034         3.1          1.5         0.2    setosa
#   5:    0.8620690         3.6          1.4         0.2    setosa
# 146:    0.8481013         3.0          5.2         2.3 virginica
# 147:    0.7974684         2.5          5.0         1.9 virginica
# 149:    0.7848101         3.4          5.4         2.3 virginica
# 150:    0.7468354         3.0          5.1         1.8 virginica

df <- data.frame(dt) ## It's possible (but not necessary) to coerce back to
                     ## a plain old data.frame
Run Code Online (Sandbox Code Playgroud)


jor*_*ran 5

我严格地解释了你想要除以最大值的愿望.

一种选择:

aggregate(iris$Sepal.Length,list(iris$Species),FUN = function(x) x/max(x))
Run Code Online (Sandbox Code Playgroud)

而另一个,使用ddplyplyr(和缩放所有列在一次:

ddply(iris,.(Species),colwise(function(x){x / max(x)}))
Run Code Online (Sandbox Code Playgroud)

而且更像@Dwin的ave例子,保持其他列相同,但使用ddply:

ddply(iris,.(Species),transform,Sepal.Length = Sepal.Length / max(Sepal.Length))
Run Code Online (Sandbox Code Playgroud)