admin管理员组

文章数量:1313729

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

本文标签: rTurn dataframe with frequency into a frequency table for chisquare testStack Overflow