简体   繁体   中英

chi square test - R dyplr

I have the following dataframe:

data = data.frame(group = c("conse", "dem", "schoo"),
                  f = c(43, 30, 36),
                  m = c(rep(29, 17, 36))

I would like to apply a chi square test to check whether the proportion of females and males is comparable in the three groups.

But when I write the following code:

data_chi = data%>%
  chisq.test()

I get an error message saying "Error in sum(x): invalid 'type' (character) of argument"

I have tried to transform my table as a tibble and nothing happened then (not even an error message).

Could you help me find a solution?

Thanks a lot!

You need to drop the group column, since the Chi square test will only work on numeric data, and doesn't know what to do with a character column

data = data.frame(group = c("conse", "dem", "schoo"),
                  f = c(43, 30, 36),
                  m = c(rep(29, 17, 36)))

library(dplyr)

data %>%
  select(-group) %>%
  chisq.test()
#> 
#>  Pearson's Chi-squared test
#> 
#> data:  .
#> X-squared = 12.44, df = 35, p-value = 0.9998

Created on 2023-01-25 with reprex v2.0.2

another option

library(magrittr)
data <- data.frame(
  group = c("conse", "dem", "schoo"),
  f = c(43, 30, 36),
  m = c(29, 17, 36)
)

data %$% chisq.test(data[-1])
#> 
#>  Pearson's Chi-squared test
#> 
#> data:  data[-1]
#> X-squared = 2.5522, df = 2, p-value = 0.2791

Created on 2023-01-25 with reprex v2.0.2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM