本文介绍了R中按组列出的因子水平的百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算一组因素中不同水平的因素所占的百分比.

I am trying to calculate the percentage of different levels of a factor within a group.

我嵌套了数据,希望看到每个国家中私立学校的比例为2级.

I have nested data and would like to see the percentage of schools in each country is a private schools (factor with 2 levels).

但是,我不知道该怎么做.

However, I cannot figure out how to do that.

# my data:
CNT <- c("A", "A", "A", "A", "A", "B", "B", "B", "C", "C", "C", "C", "C", "C", "D", "D",  
"D", "D", "D", "D")
SCHOOL <- c(1:5, 1:3, 1:6, 1:6)
FACTOR <- as.factor(c(1,2,1,2,1,1,1,2,1,2,2,2,1,1,1,1,1,1,1,1))
mydata <- data.frame(CNT, SCHOOL, FACTOR)
head(mydata)

我想要一个列,其中包含每个国家/地区中因子水平(假设为1)的百分比.

I want a column with the percentage of one level of the Factor (lets say 1) within each country.

推荐答案

另一种解决方案(带有base-R):

Another solution (with base-R):

prop.table(table(mydata$CNT, mydata$FACTOR), margin = 1)
            1         2
  A 0.6000000 0.4000000
  B 0.6666667 0.3333333
  C 0.5000000 0.5000000
  D 1.0000000 0.0000000

这篇关于R中按组列出的因子水平的百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 14:48