pivot a dataset in r

To pivot a dataset in R, you can use the pivot_longer() or pivot_wider() functions from the tidyr package.

Here is an example of how to pivot a dataframe using pivot_longer():

main.r
library(tidyr)

# create sample dataframe
df <- data.frame(id = 1:3, 
                 q1 = c("Yes", "No", "Yes"), 
                 q2 = c("No", "Yes", "No"), 
                 q3 = c(2, 5, 3))

# pivot dataframe to longer format
df_longer <- pivot_longer(df, cols = starts_with("q"),
                          names_to = "question", values_to = "answer")

358 chars
13 lines

In the above code, we first load the tidyr package. Then, we create a sample dataframe with columns for id, q1, q2, and q3. We then use pivot_longer() to pivot the dataframe from a wide format to a longer format, using starts_with("q") to select all columns that start with "q". The names_to argument specifies the new column name for the pivoted column names, while the values_to argument specifies the name for the new column that contains the pivoted values.

Here is an example of how to pivot a dataframe using pivot_wider():

main.r
library(tidyr)

# create sample dataframe
df <- data.frame(id = c(1,1,2,2), 
                 year = c(2019, 2020, 2019, 2020),
                 value = c(10, 20, 12, 22))

# pivot dataframe to wider format
df_wider <- pivot_wider(df, names_from = "year", values_from = "value")
279 chars
10 lines

In the above code, we first load the tidyr package. Then, we create a sample dataframe with columns for id, year, and value. We then use pivot_wider() to pivot the dataframe from a long format to a wider format, using names_from to specify the column to use for the new column names, and values_from to specify the column containing the values to pivot.

These functions provide a simple and efficient way to pivot dataframes in R.

related categories

gistlibby LogSnag