• Post author:
  • Post category:R Programming
  • Post last modified:March 27, 2024
  • Reading time:8 mins read
You are currently viewing How to Transpose a Data Frame in R?

In R, you can use the t() function to transpose a DataFrame. Transposing a DataFrame in R refers to swapping rows and columns. In this article, I will explain how to transpose a DataFrame using several methods such as the R base t() function, the functions transpose(), and rorate_df() from data.table, and sjmisc packages respectively.

Key points-

  • The primary function for transposing a DataFrame in R is t(). It swaps rows and columns, converting the DataFrame into its transpose.
  • Other packages, such as data.table and sjmisc, provide specialized functions like transpose() and rotate_df() for DataFrame transposition.
  • After transposing, it’s important to redefine column and row names using colnames() and rownames() for clarity.
  • To preserve both row and column names, use as.data.frame(t(df)) or similar methods to convert the transposed matrix back into a DataFrame.
  • When transposing selectively, use setNames() to set meaningful column names, especially if the original row names should become column headers.

Let’s create an R DataFrame, run this, and explore the output. If you already have data in CSV you can easily import CSV files to R DataFrame. Also, refer to Import Excel File into R.


# Create DataFrame
df <- data.frame(
  id = c(10,11,12,13,14),
  name = c('sai','ram','deepika','sahithi','kumar'),
  gender = c('M','M','F','F','M'),
  dob = as.Date(c('1990-10-02','1981-3-24','1987-6-14','1985-8-16', '1995-03-02')),
  state = c('CA','NY',NA,NA,'DC'),
  row.names=c('r1','r2','r3','r4','r5')
)
df

The above code creates a data frame named df with five columns (id, name, gender, dob, state) and five rows (r1 to r5). The columns include numerical and character data and one column (dob) is of Date type. This example yields the below output.

transpose data frame in r

Transpose Data Frame in R base t() function

You can transpose the data frame using a fundamental method of the R base t() function. This function transposes the original data frame and returns the transposed matrix where the columns are rows and vice versa of the original data frame. You can use the as.data.frame() to convert the transposed matrix into a DataFrame. This method can preserve the row and column names of the transposed data frame.


# Transpose the data frame using t() function
transposed_df <- as.data.frame(t(df))
transposed_df

# Type of the object
class(transposed_df)

Yields below output.

transpose data frame in r

R Transpose DataFrame Keep First Column as Header

Alternatively, you can use the R base t() function and the setNames() function to keep the first column values of the original data frame as a header of the transposed data frame. transpose the data frame.


# To keep the first column as a header of transposed data frame
transformed_df = setNames(data.frame(t(df[,-1])), df[,1])
transformed_df

The above code has returned a transposed data frame transformed_df. The setNames() function is used to set column names for the transposed DataFrame, using the first column of the original DataFrame (df[,1]). This example yields the below output.


# Output:
               10         11         12         13         14
name          sai        ram    deepika    sahithi      kumar
gender          M          M          F          F          M
dob    1990-10-02 1981-03-24 1987-06-14 1985-08-16 1995-03-02
state          CA         NY       <NA>       <NA>         DC

Transpose Data Frame in R using transpose()

Similarly, you can use transpose() function from the data.table package to transport the data frame. Before going to use data.table functions we need to install this package as install.packages('data.table') then load it using the library(data.table) on the R studio console.

This function returns the transposed data frame with new column names and row names. You can use the rownames() and the colnames() functions to redefine the column names and row names of the transposed data frame. The below example also includes redefining column and row names for clarity.


# Transpose data frame using transpose()
# Load data.table
library(data.table)
transposed_df <- transpose(df)

# Redifine the names column and row
rownames(transposed_df) <- colnames(df)
colnames(transposed_df) <- rownames(df)
transposed_df 

Yields the below output.


# Output:
         r1   r2      r3      r4    r5
id       10   11      12      13    14
name    sai  ram deepika sahithi kumar
gender    M    M       F       F     M
dob    7579 4100    6373    5706  9191
state    CA   NY    <NA>    <NA>    DC

Using rotate_df() from sjmisc package

Finally, you can use the rotate_df() function from the sjmisc package to transpose the data frame. Before going to use sjmisc functions we need to install this package as install.packages('<code>sjmisc‘) then load it using the library(<code>sjmisc) on the R studio console. This function utilizes the cn argument to use the first column as headers directly.


# To transpose the data frame using sjmisc packages
transformed_df <- rotate_df(df, cn = T)
transformed_df

Yields the below output.


# Output:
               10         11         12         13         14
name          sai        ram    deepika    sahithi      kumar
gender          M          M          F          F          M
dob    1990-10-02 1981-03-24 1987-06-14 1985-08-16 1995-03-02
state          CA         NY       <NA>       <NA>         DC

Conclusion

In this article, I have explained transposing a data frame in R is a common operation, and there are multiple approaches to achieve it. Provided examples cover different methods, from basic functions like t() to specialized functions in packages like data.table and sjmisc. Depending on the specific requirements and preferences, users can choose the method that best suits their needs. The ability to transpose data frames is a valuable skill for reshaping data and enhancing its usability in various data analysis tasks.

Happy Learning!!

Vijetha

Vijetha is an experienced technical writer with a strong command of various programming languages. She has had the opportunity to work extensively with a diverse range of technologies, including Python, Pandas, NumPy, and R. Throughout her career, Vijetha has consistently exhibited a remarkable ability to comprehend intricate technical details and adeptly translate them into accessible and understandable materials. Follow me at Linkedin.