convert columns into rows in r

To convert columns into rows in R, we can use the pivot_longer() function from the tidyr package in the tidyverse library. This function allows us to reshape our data from wide format to long format.

Here's an example code to convert the columns "var1", "var2", "var3" into rows:

main.r
library(tidyverse)

# create example data.frame
df <- data.frame(id = 1:3, var1 = c(4, 5, 6), var2 = c(7, 8, 9), var3 = c(10, 11, 12)) 

# view the original data.frame
df
#>   id var1 var2 var3
#> 1  1    4    7   10
#> 2  2    5    8   11
#> 3  3    6    9   12

# reshape the data.frame using pivot_longer()
df_long <- df %>% 
  pivot_longer(cols = c(var1, var2, var3), names_to = "variable", values_to = "value")

# view the new data.frame
df_long
#> # A tibble: 9 x 3
#>      id variable value
#>   <int> <chr>    <dbl>
#> 1     1 var1         4
#> 2     1 var2         7
#> 3     1 var3        10
#> 4     2 var1         5
#> 5     2 var2         8
#> 6     2 var3        11
#> 7     3 var1         6
#> 8     3 var2         9
#> 9     3 var3        12
758 chars
31 lines

In the code above, we first create an example data.frame with the columns "id", "var1", "var2", and "var3". We then use the pivot_longer() function to reshape the data, specifying the columns to pivot with cols, the new column name for the pivoted columns with names_to, and the new column name for the values with values_to.

The resulting data.frame df_long has three columns, "id", "variable", and "value". The original columns "var1", "var2", and "var3" have been converted into rows in the "variable" column, and their values have been placed in the "value" column.

gistlibby LogSnag