- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- How to convert values greater than a threshold into 1 in R data frame column?
- How to convert first letter into capital in R data frame column?
- How to convert a matrix into a data frame with column names and row names as variables in R?
- How to match a column in a data frame with a column in another data frame in R?
- How to extract a single column of an R data frame as a data frame?
- How to separate two values in single column in R data frame?
- How to convert multiple columns in an R data frame into a single numerical column along with a column having column names as factor?
- How to convert multiple columns into single column in an R data frame?
- How to subtract column values from column means in R data frame?
- How to create a boxplot of single column in R data frame with column name?
- How to save column means into a data frame in R?
- How to convert a data frame into table for two factor columns and one numeric column in R?
- How to repeat column values in R data frame by values in another column?
- How to convert values in alternate rows to negative in R data frame column?
- How to concatenate column values and create a new column in an R data frame?

Advertisements