最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

r - Turn dataframe with frequency into a frequency table for chi-square test - Stack Overflow

programmeradmin1浏览0评论

I have this dataframe:

structure(list(health_pa = c(0, 0, 1, 1), matt_ne = c("matt_ne", 
"total", "matt_ne", "total"), n = c(425L, 1227L, 14L, 58L)), class = c("rowwise_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -4L), groups = structure(list(
    .rows = structure(list(1L, 2L, 3L, 4L), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), row.names = c(NA, -4L), class = c("tbl_df", 
"tbl", "data.frame")))

I'd like to turn it into a table like this so I can run a chi-square test:

matt_ne total
0 425 1227
1 14 58

I have this dataframe:

structure(list(health_pa = c(0, 0, 1, 1), matt_ne = c("matt_ne", 
"total", "matt_ne", "total"), n = c(425L, 1227L, 14L, 58L)), class = c("rowwise_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -4L), groups = structure(list(
    .rows = structure(list(1L, 2L, 3L, 4L), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), row.names = c(NA, -4L), class = c("tbl_df", 
"tbl", "data.frame")))

I'd like to turn it into a table like this so I can run a chi-square test:

matt_ne total
0 425 1227
1 14 58

If possible can I do this in a dplyr pipe?

Share Improve this question edited Jan 30 at 15:01 Ryan Gary asked Jan 30 at 14:49 Ryan GaryRyan Gary 1579 bronze badges 2
  • Your code fragment is incomplete. Something is missing from the start. Also, your column names suggest that you actually observed (eg) 1227 occurences of "row category 0" in total, 425 of which were "column category matt_ne" and 802 were "column category not matt_ne". If that is indeed the case, you might want to reconsider your desired output. – Limey Commented Jan 30 at 14:59
  • Sorry I've corrected the code – Ryan Gary Commented Jan 30 at 15:02
Add a comment  | 

1 Answer 1

Reset to default 1

With your data assigned to df, you can do the following to get to your desired structure:

library(tidyverse)
df %>% ungroup() %>%
  pivot_wider(values_from = n, names_from = matt_ne) %>% 
  column_to_rownames("health_pa")

Created on 2025-01-30 with reprex v2.1.1

发布评论

评论列表(0)

  1. 暂无评论