Transpose Data Matrix & Maintain First Variable as Column Names in R (Example Code)
In this tutorial, I’ll illustrate how to transpose a data set and use the first variable as column names in the R programming language.
Introduction of Example Data
my_df <- data.frame(v1 = paste0("col", 1:5), # Example data v2 = letters[1:5], v3 = letters[6:10], v4 = letters[11:15], v5 = letters[16:20]) my_df # v1 v2 v3 v4 v5 # 1 col1 a f k p # 2 col2 b g l q # 3 col3 c h m r # 4 col4 d i n s # 5 col5 e j o t |
my_df <- data.frame(v1 = paste0("col", 1:5), # Example data v2 = letters[1:5], v3 = letters[6:10], v4 = letters[11:15], v5 = letters[16:20]) my_df # v1 v2 v3 v4 v5 # 1 col1 a f k p # 2 col2 b g l q # 3 col3 c h m r # 4 col4 d i n s # 5 col5 e j o t
Example: Apply setNames & data.frame Functions to Transpose Data Frame & Keep First Column as Header
my_df_trans <- setNames(data.frame(t(my_df[ , - 1])), # Transposing data my_df[ , 1]) my_df_trans # Display new data # col1 col2 col3 col4 col5 # v2 a b c d e # v3 f g h i j # v4 k l m n o # v5 p q r s t |
my_df_trans <- setNames(data.frame(t(my_df[ , - 1])), # Transposing data my_df[ , 1]) my_df_trans # Display new data # col1 col2 col3 col4 col5 # v2 a b c d e # v3 f g h i j # v4 k l m n o # v5 p q r s t
Further Resources & Related Articles
Here, you can find some additional resources on topics such as lists and variables.