To convert columns into rows in R, we can use the pivot_longer()
function from the tidyr
package in the tidyverse
library. This function allows us to reshape our data from wide format to long format.
Here's an example code to convert the columns "var1", "var2", "var3" into rows:
main.r758 chars31 lines
In the code above, we first create an example data.frame
with the columns "id", "var1", "var2", and "var3". We then use the pivot_longer()
function to reshape the data, specifying the columns to pivot with cols
, the new column name for the pivoted columns with names_to
, and the new column name for the values with values_to
.
The resulting data.frame df_long
has three columns, "id", "variable", and "value". The original columns "var1", "var2", and "var3" have been converted into rows in the "variable" column, and their values have been placed in the "value" column.
gistlibby LogSnag