Convert rows to columns and columns to rows using R

I have a dataframe with unique row names and unique column names. I want to convert rows to columns and columns to 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") ) 

leads to the following:

 > starting_df abc 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 to another data frame containing exactly the same data, except that there used to be columns and vice versa:

 > final_df ABCD a 1 2 3 4 b 0.02 0.04 0.06 0.08 c Aaaa Bbbb Cccc Dddd 
+6
source share
1 answer

Just use the basic transpose function t wrapped in as.data.frame :

 final_df <- as.data.frame(t(starting_df)) final_df ABCD 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. Since Mark suggested wrapping it with as.data.frame , return the data frame instead of the matrix. Thanks!

+14
source

Source: https://habr.com/ru/post/982903/


All Articles