How to convert a column values to column names in R?


To convert a column values to column names, we can use dcast function of reshape2 package. For example, if we have a data frame called df that contains two columns say x and y, where x is categorical and y is numerical. Now if we want to convert the categories in x as column names then it can be done as dcast(df,y~x).

Example1

Consider the below data frame −

Live Demo

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

Output

   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

Loading reshape2 package and converting values in x1 to column names −

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

Using x2 as value column: use value.var to override.

Aggregation function missing: defaulting to length

Output

   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

Example2

Live Demo

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

Output

   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

Converting values in Gender to column names −

> dcast(df2,Rate~Gender)

Using Rate as value column: use value.var to override. 

Aggregation function missing: defaulting to length

Output

   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

Updated on: 05-Mar-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements