我想知道是否可以在执行分组后应用 ggplot2 转换(数据)。

例子:

这是 iris 的 qqplot 按物种:

ggplot(iris, aes(sample=Sepal.Width, col=Species)) +
    stat_qq() +
    ggtitle('qqnorm of Sepal Width')

我想通过 Sepal.Width 转换 (x - mean(x))/sd(x) s:
normalize = function (x) (x - mean(x))/sd(x)
ggplot(iris, aes(sample=normalize(Sepal.Width), col=Species)) +
    stat_qq() +
    ggtitle('qqnorm of Sepal Width, normalized globally')

请注意,这在标准化中使用了全局均值/标准差,而不是每组均值/标准差(如果您编写 aes(sample=(Sepal.Width - mean(Sepal.Width))/sd(Sepal.Width)) 而不是将其隐藏在 normalize 中,也会发生同样的情况。

问题 :有没有办法在每个组(物种)的 中应用 normalize

我可以用 ddply 做到这一点,只是想知道是否有一种优雅的方法可以在 ggplot 调用中对我的数据应用仿射变换,其中变换参数是每组的。
ggplot(ddply(iris, .(Species), mutate, y=normalize(Sepal.Width)),
             aes(sample=y, col=Species)) +
    stat_qq() +
    ggtitle('qqnorm of Sepal.Width, normalized within-group')

最佳答案

您也可以将函数 normalize 更改为采用银色 by 。这使得 normalize 函数更加复杂,但简化了 ggplot 调用(与 plyr 解决方案相比)。有关如何定义规范化的建议,请参见下文。

# new normalize command
normalize <- function(x, by='none'){
  unsplit(lapply(unique(by), function(id) scale(x[by==id])), by)
}
# global normalization
ggplot(iris, aes(sample=normalize(Sepal.Width), col=Species)) +
  stat_qq() +
  ggtitle('qqnorm of Sepal Width, normalized globally')
# groupe-wise normalization
ggplot(iris, aes(sample=normalize(Sepal.Width, by=Species), col=Species)) +
  stat_qq() +
  ggtitle('qqnorm of Sepal Width, normalized by species')

关于r - 按组转换数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27240655/

10-12 19:53