如何按R中的列拆分数据框?
如果我们有一个包含一些重复值或代表类别的数据框列,那么我们可能希望基于该列拆分数据框。
例如,如果我们有一个名为 df 的数据框,其中包含一列 Col,那么我们可以使用下面给出的命令按 Col 拆分数据框 -
split(df,df$Col)
示例 1
以下代码段创建了一个示例数据框 -
Group<-sample(c("Male","Female"),20,replace=TRUE)Score<-rpois(20,8)
df1<-data.frame(Group,Score)
df1
创建以下数据框 -
Group Score1 Male 8
2 Female 6
3 Female 5
4 Female 7
5 Female 12
6 Female 10
7 Female 9
8 Male 9
9 Male 10
10 Female 13
11 Female 4
12 Male 11
13 Female 5
14 Male 6
15 Female 9
16 Male 9
17 Female 5
18 Female 8
19 Male 3
20 Female 5
要根据 Group 列拆分 df1,请将以下代码添加到上述代码段中 -
Group<-sample(c("Male","Female"),20,replace=TRUE)输出结果Score<-rpois(20,8)
df1<-data.frame(Group,Score)
split(df1,df1$Group)
如果您将上述所有给定的片段作为单个程序执行,它会生成以下输出 -
$FemaleGroup Score
2 Female 6
3 Female 5
4 Female 7
5 Female 12
6 Female 10
7 Female 9
10 Female 13
11 Female 4
13 Female 5
15 Female 9
17 Female 5
18 Female 8
20 Female 5
$Male
Group Score
1 Male 8
8 Male 9
9 Male 10
12 Male 11
14 Male 6
16 Male 9
19 Male 3
示例 2
以下代码段创建了一个示例数据框 -
Class<-sample(c("I","II","III"),20,replace=TRUE)Number_of_Customers<-sample(1:10,20,replace=TRUE)
df2<-data.frame(Class,Number_of_Customers)
df2
创建以下数据框 -
Class Number_of_Customers1 II 2
2 I 10
3 III 2
4 III 4
5 III 5
6 III 7
7 III 10
8 II 4
9 II 9
10 I 7
11 III 4
12 I 1
13 I 1
14 I 1
15 III 5
16 II 5
17 II 9
18 II 8
19 II 8
20 I 9
要根据 Class 列拆分 df2,请将以下代码添加到上面的代码段中 -
Class<-sample(c("I","II","III"),20,replace=TRUE)输出结果Number_of_Customers<-sample(1:10,20,replace=TRUE)
df2<-data.frame(Class,Number_of_Customers)
split(df2,df2$Class)
如果您将上述所有给定的片段作为单个程序执行,它会生成以下输出 -
$IClass Number_of_Customers
2 I 10
10 I 7
12 I 1
13 I 1
14 I 1
20 I 9
$II
Class Number_of_Customers
1 II 2
8 II 4
9 II 9
16 II 5
17 II 9
18 II 8
19 II 8
$III
Class Number_of_Customers
3 III 2
4 III 4
5 III 5
6 III 7
7 III 10
11 III 4
15 III 5
以上是 如何按R中的列拆分数据框? 的全部内容, 来源链接: utcz.com/z/353554.html