R:转换groupby数据

R: transform groupby data

我需要创建一个 table,其中行 = 房屋,列 = 男人、女人和总数。我使用了 group_by 函数,但它向我显示了错误的数据结构:

got_chars_bar <- got_chars %>% group_by(house, male) %>% count(house, sort = TRUE)

结果是:

My data after this operation

您可以在此处查看初始数据框:https://gitlab.com/hse_mar/mar211s/-/raw/main/data/character-predictions_pose.csv 或在此处查看图片(

我只想要行 = 房屋和列(男性、女性和总计)。请帮助我,我今天有截止日期((

尝试 pivot_wider:

df <- data.frame(
  house = c("uk", "uk", "NW", "HF", "HS", "HF"),
  male = c(1,0,1,1,1,0),
  n = c(245,182,79,54,49,43)
)

df2 <- df %>% 
  pivot_wider(names_from = male, values_from = n, values_fill = NA) %>% 
  mutate(total = `0` + `1`)

希望有用

library(dplyr)
library(reshape2)
df <- read.csv("path to csv")
dfnew<- df %>% select(house, male)%>%mutate(gender= ifelse(male==1, "MALE", "FEMALE"))
myvars <- c("house", "gender")
dfnew <- dfnew[myvars]
out <- data.frame(addmargins(table(dfnew), 2))
newdf<- dcast(out, house~gender)

output :


[![enter image description here][1]][1]