r - 按组转换数据

标签 r ggplot2

我想知道是否可以在执行分组后应用 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/

相关文章:

r - ggplot2::geom_segment。如何设置多个尺寸,比如 c(10,12)?

r - 手动设置 scale_fill_distiller() 的比例

r - 如何在 R 或 Stata 中绘制相对频率

r - ggplot2 在 R 3.0.2 上安装失败

r - 如何在条件发生后过滤出每组的行

r - 改变列表的逻辑

r - 在R中获取伴随矩阵

r - 从 dlply 内部调用 lm 抛出 "0 (non-NA) cases"错误 [r]

r - lmer 但不是 glmer : Error in checkNlevels(reTrms$flist, n = n, control) 错误的解释:

R:适合显示具有倾斜计数的数据的图