How to convert a data frame into two column data frame with values and column name as variable in R?


To convert a data frame into two column data frame with values and column name as variable in R, we can follow the below steps −

  • First of all, create a data frame.

  • Then, use stack function to convert data frame.

Example

Create the data frame

Let’s create a data frame as shown below −

x<-rpois(10,5)
y<-rpois(10,2)
z<-rpois(10,1)
df<-data.frame(x,y,z)
df

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

   x y z
1  3 3 3
2  3 3 0
3  7 3 3
4  3 1 0
5  6 5 1
6  6 0 0
7  5 4 3
8  4 4 1
9  6 1 0
10 2 6 0

Convert the data frame

Using stack function to convert data frame df into two column data frame with values and column name as variable as shown below −

x<-rpois(10,5)
y<-rpois(10,2)
z<-rpois(10,1)
df<-data.frame(x,y,z)
stack(df)

Output

  values ind
1   5    x
2   7    x
3   7    x
4   3    x
5   4    x
6   3    x
7   4    x
8   5    x
9   6    x
10 10    x
11  3    y
12  3    y
13  3    y
14  2    y
15  2    y
16  2    y
17  4    y
18  1    y
19  1    y
20  1    y
21  1    z
22  0    z
23  0    z
24  1    z
25  0    z
26  1    z
27  1    z
28  0    z
29  2    z
30  1    z

Updated on: 11-Nov-2021

774 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements