如图所示,我有一个名为 df 的数据。我想对“值”列应用夏皮罗测试,但基于不同的颜色类别。在下面,您可以看到我的代码出现以下错误“由错误引起:!
shapiro.test(value)
必须是向量,而不是对象。”。我会提出你的建议。
df %>%
group_by(color) %>%
summarise(shapiro.test(value))
我们可以将它包装在一个
list
中,因为输出是一个list
library(dplyr)
df %>%
group_by(color) %>%
summarise(out = list(shapiro.test(value)), .groups = 'drop')
或者另一种选择是使用
tibble
和 tidy
tibble转换为
unnest
library(tidyr)
df %>%
reframe(out = broom::tidy(shapiro.test(value)), .by = 'color') %>%
unnest(where(is_tibble))
当有简单的基本 R 解决方案时,此站点上的用户似乎过度使用了
tidyverse
解决方案。这是一个,带有一些模拟数据:
df <- data.frame(value=rnorm(200), color=c(rep("blue", 100), rep("red", 100)))
with(df, tapply(value, color, shapiro.test))
$blue
Shapiro-Wilk normality test
data: X[[i]]
W = 0.98655, p-value = 0.4078
$red
Shapiro-Wilk normality test
data: X[[i]]
W = 0.98544, p-value = 0.3417
with
和它的表亲 within
非常有用,代码干净,似乎没有得到充分利用。
使用本地管道的替代语法是
df |> with(tapply(value, color, shapiro.test))
导致与上面完全相同的输出。