如何在R数据框中的分类列中找到类别计数?
如果我们在R数据帧中有两个类别列,则可以找到相对于另一列中每个类别的每个类别的频率/计数。这将有助于我们比较所有类别的频率。要查找类别的计数,我们可以使用表函数,如以下示例所示。
例1
考虑以下数据帧-
x1<−sample(c("Child","Teen","Adult","Old"),20,replace=TRUE)输出结果x2<−sample(c("Unemployed","Employed"),20,replace=TRUE)
df1<−data.frame(x1,x2)
df1
x1 x21 Old Unemployed
2 Child Unemployed
3 Adult Employed
4 Adult Unemployed
5 Adult Employed
6 Teen Employed
7 Old Employed
8 Child Unemployed
9 Child Employed
10 Adult Unemployed
11 Child Unemployed
12 Old Employed
13 Child Unemployed
14 Child Employed
15 Teen Employed
16 Adult Employed
17 Adult Unemployed
18 Old Employed
19 Adult Unemployed
20 Child Employed
在df1的两列中找到类别的计数-
示例
table(df1$x1,df1$x2)输出结果
Employed UnemployedAdult 3 4
Child 3 4
Old 3 1
Teen 2 0
例2
y1<−sample(c("Married","Unmarried"),20,replace=TRUE)输出结果y2<−sample(c("Satisfied","Not-Satisfied"),20,replace=TRUE)
df2<−data.frame(y1,y2)
df2
y1 y21 Married Not-Satisfied
2 Unmarried Not-Satisfied
3 Married Not-Satisfied
4 Unmarried Not-Satisfied
5 Married Satisfied
6 Married Not-Satisfied
7 Unmarried Satisfied
8 Married Satisfied
9 Unmarried Not-Satisfied
10 Unmarried Not-Satisfied
11 Unmarried Not-Satisfied
12 Unmarried Not-Satisfied
13 Married Satisfied
14 Married Satisfied
15 Married Satisfied
16 Married Not-Satisfied
17 Married Satisfied
18 Unmarried Satisfied
19 Married Satisfied
20 Married Satisfied
在df2的两列中找到类别计数-
示例
table(df2$y1,df2$y2)输出结果
Not−Satisfied SatisfiedMarried 4 8
Unmarried 6 2
以上是 如何在R数据框中的分类列中找到类别计数? 的全部内容, 来源链接: utcz.com/z/340398.html