Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to transpose a data.frame in R and to set one of the columns to be the header for the new transposed table?

Tags:

What is the best way to transpose a data.frame in R and to set one of the columns to be the header for the new transposed table? I have coded up a way to do this below. As I am still new to R. I would like suggestions to improve my code as well as alternatives that would be more R-like. My solution is also unfortunately a bit hard coded (i.e. the new column headings are in a certain location).

# Assume a data.frame called fooData # Assume the column is the first column before transposing  # Transpose table fooData.T <- t(fooData)  # Set the column headings colnames(fooData.T) <- test[1,]  # Get rid of the column heading row fooData.T <- fooData.T[2:nrow(fooData.T), ]  #fooData.T now contains a transposed table with the first column as headings 
like image 337
themartinmcfly Avatar asked Jul 11 '11 03:07

themartinmcfly


People also ask

How do I transpose a Dataframe 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 you flip rows and columns in a Dataframe 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)).

What is the transpose function in R?

Transpose of a matrix is an operation in which we convert the rows of the matrix in column and column of the matrix in rows.

How do I transpose a list in R?

Description. Transpose turns a list-of-lists "inside-out"; it turns a pair of lists into a list of pairs, or a list of pairs into pair of lists. For example, if you had a list of length n where each component had values a and b , transpose() would make a list with elements a and b that contained lists of length n.


2 Answers

Well you could do it in 2 steps by using

# Transpose table YOU WANT fooData.T <- t(fooData[,2:ncol(fooData)])  # Set the column headings from the first column in the original table colnames(fooData.T) <- fooData[,1]  

The result being a matrix which you're probably aware of, that's due to class issues when transposing. I don't think there will be a single line way to do this given the lack of naming abilities in the transpose step.

like image 79
nzcoops Avatar answered Sep 27 '22 18:09

nzcoops


You can do it even in one line:

fooData.T <- setNames(data.frame(t(fooData[,-1])), fooData[,1]) 

There are already great answers. However, this answer might be useful for those who prefer brevity in code.

like image 27
Mu Afzal Avatar answered Sep 27 '22 18:09

Mu Afzal