Normality and fragmentation of the sample

Asked

Viewed 49 times

4

I’m having a problem with an analysis of shapiro.test in the R. I want to analyze the normality of a certain variable x, but I want to do this in stratified samples that together correspond to variable y.

set.seed(1)

df_1 <- data.frame(
  x = rnorm(n = 30, mean = 10, sd = 1), 
  y = sample(x = 1:3, size = 30, replace = TRUE)
)
  • It is possible to analyze x for each group that is in y?

3 answers

5

You can use tapply:

set.seed(1)

df_1 <- data.frame(
  x = rnorm(n = 30, mean = 10, sd = 1), 
  y = sample(x = 1:3, size = 30, replace = TRUE)
)

tapply(X = df_1$x, INDEX = df_1$y, FUN = shapiro.test)

#$`1`

#Shapiro-Wilk normality test

#data:  X[[i]]
#W = 0.98473, p-value = 0.9841


#$`2`

#Shapiro-Wilk normality test

#data:  X[[i]]
#W = 0.91978, p-value = 0.3552


#$`3`

#Shapiro-Wilk normality test

#data:  X[[i]]
#W = 0.90565, p-value = 0.2164

3

It is possible to use packages tidyverse and broom and get the results organized in a data frame:

library(tidyverse)
library(broom)

set.seed(1)

df_1 <- data.frame(
  x = rnorm(n = 30, mean = 10, sd = 1), 
  y = sample(x = 1:3, size = 30, replace = TRUE)
)

df_1 %>%
  group_by(y) %>%
  do(tidy(shapiro.test(.$x)))
#> # A tibble: 3 x 4
#> # Groups:   y [3]
#>       y statistic p.value method                     
#>   <int>     <dbl>   <dbl> <chr>                      
#> 1     1     0.967   0.864 Shapiro-Wilk normality test
#> 2     2     0.928   0.361 Shapiro-Wilk normality test
#> 3     3     0.924   0.422 Shapiro-Wilk normality test

Created on 2020-09-30 by the reprex package (v0.3.0)

2

Similar to reply from Marcus Nunes, but with data.table:

library(data.table)

setDT(df_1)

> df_1[, shapiro.test(x), by = y]
   y  statistic    p.value                      method data.name
1: 2 0.8751273 0.04955792 Shapiro-Wilk normality test         x
2: 1 0.9783130 0.95095668 Shapiro-Wilk normality test         x
3: 3 0.9572601 0.76925217 Shapiro-Wilk normality test         x

Browser other questions tagged

You are not signed in. Login or sign up in order to post.