Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting rows into columns and columns into rows using R

Tags:

I have a dataframe with unique row names and unique column names. I want to convert the rows into columns and column into rows.

For example, this code:

starting_df <- data.frame(row.names= c(LETTERS[1:4]),                           a = c(1:4),                           b = seq(0.02,0.08,by=0.02),                           c = c("Aaaa","Bbbb","Cccc","Dddd")                 ) 

results in the following:

> starting_df   a    b    c A 1 0.02 Aaaa B 2 0.04 Bbbb C 3 0.06 Cccc D 4 0.08 Dddd 

I want to convert it into another data frame containing exactly the same data, except that what were formerly rows were now columns and vice versa:

> final_df      A    B    C    D a    1    2    3    4 b 0.02 0.04 0.06 0.08 c Aaaa Bbbb Cccc Dddd 
like image 352
Christopher Bottoms Avatar asked Feb 23 '15 18:02

Christopher Bottoms


People also ask

How do I convert rows to columns and columns into rows in R?

Data Visualization using R Programming Thus, to convert columns of an R data frame into rows we can use transpose function t. For example, if we have a data frame df with five columns and five rows then we can convert the columns of the df into rows by using as. data. frame(t(df)).

How do I transpose rows to columns in R?

To interchange rows with columns, you can use the t() function. For example, if you have the matrix (or dataframe) mat you can transpose it by typing t(mat) . This will, as previously hinted, result in a new matrix that is obtained by exchanging the rows and columns.

How do I convert 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).

How do I separate columns and rows in R?

To split a column into multiple columns in the R Language, we use the separator() function of the dplyr package library. The separate() function separates a character column into multiple columns with a regular expression or numeric locations.


1 Answers

Simply use the base transpose function t, wrapped with as.data.frame:

final_df <- as.data.frame(t(starting_df)) final_df      A    B    C    D a    1    2    3    4 b 0.02 0.04 0.06 0.08 c Aaaa Bbbb Cccc Dddd 

Above updated. As docendo discimus pointed out, t returns a matrix. As Mark suggested wrapping it with as.data.frame gets back a data frame instead of a matrix. Thanks!

like image 188
Christopher Bottoms Avatar answered Oct 15 '22 04:10

Christopher Bottoms