如何在R数据框中查找因子列的频数表?


如果我们在R数据框中拥有因子列,那么我们想要查找所有因子列中每个因子水平的频率。这可以使用`sapply`函数和`table`函数来完成。例如,如果我们有一个名为`df`的数据框包含一些因子列,那么可以使用命令`sapply(df,table)`创建因子列的频数表。

示例1

考虑以下数据框:

在线演示

> x1<-sample(LETTERS[1:4],20,replace=TRUE)
> x2<-sample(letters[1:4],20,replace=TRUE)
> df1<-data.frame(x1,x2)
> df1

输出

   x1 x2
1  D  a
2  D  b
3  D  c
4  D  b
5  D  c
6  C  a
7  C  a
8  B  a
9  A  a
10 C  c
11 D  a
12 D  b
13 D  b
14 A  c
15 C  b
16 D  a
17 A  b
18 A  b
19 B  c
20 C  b

在df1中查找因子列的频数表:

> sapply(df1,table)
$x1

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

A B C D
4 2 5 9

示例

$x2

输出

a b c
7 8 5

示例2

在线演示

> y1<-sample(c("India","Russia","UK"),20,replace=TRUE)
> y2<-sample(c("Male","Female"),20,replace=TRUE)
> df2<-data.frame(y1,y2)
> df2

输出

    y1      y2
1  India    Male
2  UK     Female
3  Russia   Male
4  India  Female
5  India  Female
6  India    Male
7  UK     Female
8  Russia   Male
9  UK       Male
10 India    Male
11 Russia   Male
12 UK       Male
13 UK     Female
14 India  Female
15 India  Female
16 Russia Female
17 Russia Female
18 Russia Female
19 India  Female
20 India  Female

在df2中查找因子列的频数表:

> sapply(df2,table)
$y1

输出

India Russia UK
  9     6    5

示例

$y2

输出

Female Male
  12    8

更新于:2021年3月5日

681 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告