R How to Convert Data Frame from Long to Wide Format (Example Code)
In this article, I’ll show how to convert data frames from long to wide format in R.
Creation of Example Data
my_df <- data.frame(id1 = rep(c("gr1", "gr2", "gr3", "gr4"), # Constructing data in R each = 4), id2 = letters[1:4], value = 1:16) my_df # Showing example data # id1 id2 value # 1 gr1 a 1 # 2 gr1 b 2 # 3 gr1 c 3 # 4 gr1 d 4 # 5 gr2 a 5 # 6 gr2 b 6 # 7 gr2 c 7 # 8 gr2 d 8 # 9 gr3 a 9 # 10 gr3 b 10 # 11 gr3 c 11 # 12 gr3 d 12 # 13 gr4 a 13 # 14 gr4 b 14 # 15 gr4 c 15 # 16 gr4 d 16 |
my_df <- data.frame(id1 = rep(c("gr1", "gr2", "gr3", "gr4"), # Constructing data in R each = 4), id2 = letters[1:4], value = 1:16) my_df # Showing example data # id1 id2 value # 1 gr1 a 1 # 2 gr1 b 2 # 3 gr1 c 3 # 4 gr1 d 4 # 5 gr2 a 5 # 6 gr2 b 6 # 7 gr2 c 7 # 8 gr2 d 8 # 9 gr3 a 9 # 10 gr3 b 10 # 11 gr3 c 11 # 12 gr3 d 12 # 13 gr4 a 13 # 14 gr4 b 14 # 15 gr4 c 15 # 16 gr4 d 16
Example: Applying reshape() Function to Convert Data Frame from Long to Wide Format
reshape(my_df, # Using reshape() function idvar = "id1", timevar = "id2", direction = "wide") # id1 value.a value.b value.c value.d # 1 gr1 1 2 3 4 # 5 gr2 5 6 7 8 # 9 gr3 9 10 11 12 # 13 gr4 13 14 15 16 |
reshape(my_df, # Using reshape() function idvar = "id1", timevar = "id2", direction = "wide") # id1 value.a value.b value.c value.d # 1 gr1 1 2 3 4 # 5 gr2 5 6 7 8 # 9 gr3 9 10 11 12 # 13 gr4 13 14 15 16