【问题标题】:R question: shapiro.test function not working in dplyr::summarize while other summary functions doR 问题: shapiro.test 函数在 dplyr::summarize 中不起作用,而其他摘要函数则起作用
【发布时间】:2019-09-15 04:55:22
【问题描述】:

当我尝试在我的 R DataFrame 上使用 shapiro.test 作为摘要函数时,我收到错误:

df %>% summarize_all(shapiro.test)
Error: Column `A` must be length 1 (a summary value), not 4

这是我的设置:

df = data.frame(A=sample(1:10,5), B=sample(1:10,5))
df
df %>% summarize_all(mean)
df %>% summarize_all(sd)
df %>% summarize_all(sum)
df %>% summarize_all(shapiro.test)
df$A %>% shapiro.test()

输出:

> df = data.frame(A=sample(1:10,5), B=sample(1:10,5))
> df
   A B
1  1 8
2  8 4
3  5 5
4 10 6
5  7 1
> df %>% summarize_all(mean)
    A   B
1 6.2 4.8
> df %>% summarize_all(sd)
         A        B
1 3.420526 2.588436
> df %>% summarize_all(shapiro.test)
Error: Column `A` must be length 1 (a summary value), not 4
> df$A %>% shapiro.test()

    Shapiro-Wilk normality test

data:  .
W = 0.96086, p-value = 0.814

shapiro.test 有什么特别之处使其无法在列上进行矢量化处理?

【问题讨论】:

  • 该函数返回一个长度为 4 的类 htest" 的列表。尝试定义一个函数 sh.test <- function(x) shapiro.test(x)$p.value 并在管道中使用它。
  • 查看错误消息,并查看您的夏皮罗测试的输出。摘要函数应该返回单个值,就像meansd 所做的那样。 shapiro.test 显然没有。您希望数据框中的测试输出有什么? W统计? p 值?

标签: r dataframe dplyr summarize


【解决方案1】:

您可以使用 purrr 包中的 map 作为apply 的替代方法来遍历每一列

df %>%
  map(~shapiro.test(.))

还可以考虑使用sapplylapply

df %>% 
  sapply(.,shapiro.test)


df %>% 
  lapply(.,shapiro.test)

【讨论】:

    【解决方案2】:

    刚刚知道:shaprio.test 不返回单个数字。然而,这确实有效:

    > df %>% apply(2, shapiro.test)
    $A
    
        Shapiro-Wilk normality test
    
    data:  newX[, i]
    W = 0.96086, p-value = 0.814
    
    
    $B
    
        Shapiro-Wilk normality test
    
    data:  newX[, i]
    W = 0.98396, p-value = 0.9546
    

    还有:

    > f = function(x){st = shapiro.test(x); return(st$p.value)}
    > f(df$A)
    [1] 0.8139521
    > df %>% summarise_all(f)
              A         B
    1 0.8139521 0.9546435
    

    【讨论】:

      猜你喜欢
      • 2017-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-01
      • 1970-01-01
      • 2022-07-20
      相关资源
      最近更新 更多