transform a 5 column wide dataframe to long dataframe with one column of unique values in r

You can use the pivot_longer function from the tidyr package to transform a wide dataframe to a long dataframe in R. Here is an example:

main.r
# load necessary libraries
library(tidyr)
library(dplyr)

# create a sample dataframe
df <- data.frame(
  id = c(1, 2, 3),
  column1 = c("a", "b", "c"),
  column2 = c("d", "e", "f"),
  column3 = c("g", "h", "i"),
  column4 = c("j", "k", "l"),
  column5 = c("m", "n", "o")
)

# transform the dataframe to long format
df_long <- df %>%
  pivot_longer(
    cols = -id,
    names_to = "variable",
    values_to = "value"
  )

# print the resulting dataframe
print(df_long)
469 chars
25 lines

In this example, the pivot_longer function transforms the dataframe df into a long format by melting all columns except the id column. The resulting dataframe df_long will have one column for the variable names (variable) and one column for the corresponding values (value).

The output will look like this:

main.r
# A tibble: 15 x 3
      id variable value
   <dbl> <chr>    <chr>
 1     1 column1  a     
 2     1 column2  d     
 3     1 column3  g     
 4     1 column4  j     
 5     1 column5  m     
 6     2 column1  b     
 7     2 column2  e     
 8     2 column3  h     
 9     2 column4  k     
10     2 column5  n     
11     3 column1  c     
12     3 column2  f     
13     3 column3  i     
14     3 column4  l     
15     3 column5  o     
442 chars
19 lines

This shows that the original 5 columns (column1 to column5) have been transformed into a single column variable with the corresponding values in the value column.

gistlibby LogSnag