简体   繁体   English

R 如何从 dataframe 创建包含多组计数的表?

[英]R how to create table from dataframe containing counts over groups?

I have a dataframe with the count of for instance males and females for certain groups arranged in this way:我有一个 dataframe 以这种方式排列的某些组的例如男性和女性的数量:

df <- data.frame (
  Round = c("R1", "R1", "R2", "R2"),
  N. = c(20, 10, 15,15),
  Gender = c("M", "F", "M","F")) 

How can I create a table accounting for counts over, for instance, Round and Gender?我怎样才能创建一个表来计算,例如,Round 和 Gender? I would like to show the distribution of gender for each round.我想展示每一轮的性别分布。

I have tried我努力了


table (df$Gender, df$Round)

but this is not what I need.但这不是我需要的。 I need instead to show N. by groups.相反,我需要按组显示 N.。

Something like this?是这样的吗?

library(tidyr)
pivot_wider(df, names_from = Round, values_from = N.)

  Gender    R1    R2
1 M         20    15
2 F         10    15

Or in base R with reshape :或者在 base R 中reshape

reshape(df, direction = "wide", idvar = "Gender", timevar = "Round")

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

相关问题 创建一个包含另一个数据框列中唯一值计数的 R 数据框 - Create an R dataframe containing the counts of unique values in another dataframe column 如何在R中按类别绘制包含计数的表? - How to plot a table containing counts by class in R? R:如何循环从数据框中选择基于名称的变量,并为每个变量创建一个包含第一个列均值的新变量? - R: How to loop over a name-based selection of variables from a dataframe and for each create a new variable containing the column mean of the first? 在 R 的数据框中创建组 - create groups in a dataframe in R 如何在R中随时间绘制单个数据框列中元素的计数 - How to plot counts of elements in single dataframe column over time in R 如何从R中的表中提取计数作为向量? - How to extract counts as a vector from a table in R? R中如何获取包含列表中值的行并创建计数数据框 - in R how to get rows that contain values in a list and create a dataframe of counts 在r中创建一个计数表(矩阵) - Create a table (matrix) of counts in r 如何从一个列表中创建一个 dataframe,该列表的元素是包含一个 dataframe 的列表,每个 R - How to create one dataframe from a list whose elements are lists containing one dataframe each in R 根据数据表中的组和子组的计数创建变量 - Create variable based on counts of groups and sub groups in data table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM