pivot longer one column in data frame in r

To pivot longer one column in a data frame in R, you can use the pivot_longer function from the tidyr package.

Here's an example of how to use pivot_longer on a data frame called my_df with a column my_col that we want to pivot longer:

main.r
library(tidyr)

# pivot my_col longer
my_df_longer <- pivot_longer(my_df, 
                             cols = my_col, 
                             names_to = "new_col_name", 
                             values_to = "new_col_value")
235 chars
8 lines

In the above code, cols specifies the column that we want to pivot from a wide format to a longer format. names_to specifies the name of the new column that will contain the names of the previously wide values, and values_to specifies the name of the new column that will contain the values of the previously wide values. The resulting data frame, my_df_longer, will have one row for each unique value that was previously in my_col.

Note that the tidyr package is not included in base R, so you may need to install it using install.packages("tidyr") before using it.

gistlibby LogSnag