如何在 R 中将列值转换为列名?


要将列值转换为列名,我们可以使用 reshape2 包的 dcast 函数。例如,如果我们有一个名为 df 的数据框,其中包含两列,例如 x 和 y,其中 x 是分类的,y 是数值的。现在,如果我们想将 x 中的类别转换为列名,则可以将其作为 dcast(df,y~x) 来完成。

示例 1

考虑以下数据框 -

实时演示

> x1<-sample(c("A","B","C"),20,replace=TRUE)
> x2<-rpois(20,5)
> df1<-data.frame(x1,x2)
> df1

输出

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

加载 reshape2 包并将 x1 中的值转换为列名 -

> library(reshape2)
> dcast(df1,x2~x1)

使用 x2 作为值列:使用 value.var 覆盖。

聚合函数缺失:默认为长度

输出

   x2 A B C
1  1 0 0 1
2  2 1 0 1
3  3 0 1 2
4  4 1 3 0
5  5 3 0 1
6  6 2 0 1
7  7 1 1 0
8  8 1 0 0

示例 2

实时演示

> Gender<-sample(c("Male","Female"),20,replace=TRUE)
> Rate<-rpois(20,3)
> df2<-data.frame(Gender,Rate)
> df2

输出

   Gender Rate
1    Male    2
2    Male    5
3  Female    6
4  Female    3
5    Male    5
6    Male    1
7    Male    5
8    Male    2
9  Female    3
10 Female    2
11   Male    2
12   Male    3
13 Female    6
14   Male    0
15   Male    5
16 Female    4
17   Male    3
18 Female    5
19   Male    4
20 Female    3

将“性别”中的值转换为列名 -

> dcast(df2,Rate~Gender)

使用“比率”作为值列:使用 value.var 覆盖。

聚合函数缺失:默认为长度

输出

   Rate Female Male
1    0      0    1
2    1      0    1
3    2      1    3
4    3      3    2
5    4      1    1
6    5      1    4
7    6      2    0

更新于: 2021 年 3 月 5 日

5K+ 阅读量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.