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.r358 chars13 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.r279 chars10 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.
gistlibby LogSnag