pivot longer for all columns in r

To pivot longer for all columns in R, you can use the pivot_longer function from the tidyr package. Here's an example:

main.r
# Install and load the tidyr package
install.packages("tidyr")
library(tidyr)

# Create a sample dataframe
df <- data.frame(
  id = c(1, 2, 3),
  col1 = c("a", "b", "c"),
  col2 = c("d", "e", "f"),
  col3 = c("g", "h", "i")
)

# Pivot longer for all columns
df_long <- df %>% 
  pivot_longer(
    cols = -id,  # exclude the id column
    names_to = "variable",  # name of the new column for variable names
    values_to = "value"  # name of the new column for values
  )

# Print the resulting dataframe
print(df_long)
519 chars
23 lines

This will pivot all columns except the id column to longer format. The resulting dataframe will have three columns: id, variable, and value. The variable column will contain the original column names, and the value column will contain the corresponding values.

Alternatively, you can use the everything() function to select all columns:

main.r
df_long <- df %>% 
  pivot_longer(
    cols = everything(),  # select all columns
    names_to = "variable",  
    values_to = "value"
  )
139 chars
7 lines

However, this will also include the id column, which may not be desired. To exclude the id column, you can use the - operator:

main.r
df_long <- df %>% 
  pivot_longer(
    cols = -id,  # exclude the id column
    names_to = "variable",  
    values_to = "value"
  )
133 chars
7 lines

related categories

gistlibby LogSnag