Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert one column into multiple columns

Tags:

r

I am a novice. I have a data set with one column and many rows. I want to convert this column into 5 columns. For example my data set looks like this:

Column
----
City
Nation
Area
Metro Area
Urban Area
Shanghai
China
24,000,000
1230040
4244234
New york 
America 
343423  
23423434    
343434
Etc

The output should look like this

City | Nation | Area | Metro City | Urban Area
----- -------  ------ ------------ -----------
Shangai China  2400000  1230040     4244234
New york America 343423  23423434    343434

The first 5 rows of the data set (City, Nation,Area, etc) need to be the names of the 5 columns and i want the rest of the data to get populated under these 5 columns. Please help.

like image 998
Abrar Avatar asked Jan 05 '23 07:01

Abrar


1 Answers

Here is a one liner (considering that your column is character, i.e. df$column <- as.character(df$column))

setNames(data.frame(matrix(unlist(df[-c(1:5),]), ncol = 5, byrow = TRUE)), c(unlist(df[1:5,])))

#      City  Nation       Area Metro_Area Urban_Area
#1 Shanghai   China 24,000,000    1230040    4244234
#2 New_york America     343423   23423434     343434
like image 155
Sotos Avatar answered Jan 13 '23 22:01

Sotos