如何在 R 数据框中创建包含两个因子列的表格?
r programmingserver side programmingprogramming更新于 2025/4/9 19:37:17
要在 R 数据框中创建包含两个因子列的表格,我们可以使用 table 函数和 with 函数。
例如,如果我们有一个名为 df 的数据框,其中包含两个因子列,即 F1 和 F2,那么我们可以使用以下命令 − 创建包含这两列的表格
with(df,table(F1,F2))
示例 1
以下代码片段创建了一个示例数据框 −
Group<-sample(c("G1","G2","G3"),20,replace=TRUE) Class<-sample(c("First","Second","Third"),20,replace=TRUE) df1<-data.frame(Group,Class) df1
创建以下数据框
Group Class 1 G1 First 2 G2 First 3 G3 First 4 G2 First 5 G1 Second 6 G2 Second 7 G3 Second 8 G3 Third 9 G2 First 10 G1 Third 11 G1 Second 12 G3 Second 13 G1 Second 14 G1 Third 15 G2 Second 16 G1 Second 17 G3 Third 18 G1 Second 19 G3 First 20 G1 Third
要在上面创建的数据框中创建 Group 和 Class 列表,请将以下代码添加到上面的代码片段中 −
Group<-sample(c("G1","G2","G3"),20,replace=TRUE) Class<-sample(c("First","Second","Third"),20,replace=TRUE) df1<-data.frame(Group,Class) with(df1,table(Group,Class))
输出
如果将上述所有代码片段作为单个程序执行,则会生成以下输出 −
Class Group First Second Third G1 1 5 3 G2 3 2 0 G3 2 2 2
示例 2
以下代码片段创建了一个示例数据框 −
Gender<-sample(c("Male","Female"),20,replace=TRUE) Sal_Group<-sample(c("<=10K","10K and <=20K","=20K"),20,replace=TRUE) df2<-data.frame(Gender,Sal_Group) df2
创建以下数据框
Gender Sal_Group 1 Male =20K 2 Male <=10K 3 Female <=10K 4 Male 10K and <=20K 5 Male <=10K 6 Female <=10K 7 Female 10K and <=20K 8 Female 10K and <=20K 9 Female =20K 10 Male =20K 11 Female 10K and <=20K 12 Male <=10K 13 Male =20K 14 Male =20K 15 Female 10K and <=20K 16 Male 10K and <=20K 17 Female <=10K 18 Female <=10K 19 Male =20K 20 Female 10K and <=20K
要在上面创建的数据框中创建包含"Gender"和"Sal_Group"列的表格,请将以下代码添加到上面的代码片段中 −
Gender<-sample(c("Male","Female"),20,replace=TRUE) Sal_Group<-sample(c("<=10K","10K and <=20K","=20K"),20,replace=TRUE) df2<-data.frame(Gender,Sal_Group) with(df2,table(Gender,Sal_Group))
输出
如果将上述所有代码片段作为单个程序执行,则会生成以下输出 −
Sal_Group Gender <=10K =20K 10K and <=20K Female 4 1 5 Male 3 5 2
示例 3
以下代码片段创建了一个示例数据框 −
Category<-sample(c("C1","C2","C3","C4"),20,replace=TRUE) Sample<-sample(1:4,20,replace=TRUE) df3<-data.frame(Category,Sample) df3
创建以下数据框
Category Sample 1 C4 4 2 C2 3 3 C2 3 4 C1 3 5 C3 4 6 C1 4 7 C2 1 8 C1 1 9 C1 1 10 C1 2 11 C4 3 12 C1 3 13 C4 2 14 C1 3 15 C4 2 16 C3 4 17 C1 3 18 C2 4 19 C1 2 20 C1 2
要在上面创建的数据框中创建包含 Category 和 Sample 列的表格,请将以下代码添加到上面的代码片段中 −
Category<-sample(c("C1","C2","C3","C4"),20,replace=TRUE) Sample<-sample(1:4,20,replace=TRUE) df3<-data.frame(Category,Sample) with(df3,table(Category,Sample))
输出
如果将上述所有代码片段作为单个程序执行,则会生成以下输出 −
Sample Category 1 2 3 4 C1 2 3 4 1 C2 1 0 2 1 C3 0 0 0 2 C4 0 2 1 1