简体   繁体   English

将 R 数据框转换为表格

[英]Convert R Data Frame to a table

I have a dataframe in R:我在 R 中有一个 dataframe: 在此处输入图像描述

I am trying to convert this into table with restaurant and Overall as columns and sex as a row with Freq filled in as values:我正在尝试将其转换为以 restaurant 和 Overall 为列,以 sex 为行的表格,并将 Freq 填充为值: 在此处输入图像描述

I have created the intial dataframe using xtabs: res<- xtabs(stars~restaurant+sex,aggregate(stars~restaurant+sex,data1,mean))我使用 xtabs 创建了初始 dataframe: res<- xtabs(stars~restaurant+sex,aggregate(stars~restaurant+sex,data1,mean))

and then used dcast to transpose sex column: dcast(df, restaurant+Overall ~ sex)然后使用 dcast 转置性别列: dcast(df, restaurant+Overall ~ sex) 在此处输入图像描述

But as you can see the values under male and female are populated with overall column and not freq.但是正如您所看到的,男性和女性下的值填充了整体列而不是频率。 How do I add the values to be filled with freq column?如何添加要用 freq 列填充的值? Any help is appreciated.任何帮助表示赞赏。 Thanks!谢谢!

library(tidyverse)

x <- c("burger King", "burger King","KFC", "KFC", "McDonald", "McDonald", "Taco Bell", "Taco Bell")
y <- c("Female", "male", "Female", "male","Female", "male","Female", "male")
z <- runif(8)
t <- c("1.1", "1.1", "1.2", "1.2", "1.3", "1.3", "1.4", "1.4")


df <- tibble(restuarant = x, sex = y, freq = z, overall = t)

#desired output
df %>% group_by(restuarant, overall) %>% pivot_wider(names_from = sex, values_from = freq)


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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