make a dataset with two variable name columns and one value column and then use pivot wider to change the dataframe to wide in r

To create a dataset with two variable name columns and one value column, and then use pivot_wider to change the dataframe to wide format in R, you can use the following code:

main.r
# Load necessary libraries
library(tidyr)
library(dplyr)

# Create a dataset
data <- data.frame(
  category1 = c("A", "A", "B", "B", "C", "C"),
  category2 = c("X", "Y", "X", "Y", "X", "Y"),
  value = c(10, 20, 30, 40, 50, 60)
)

# Print the original dataset
print(data)

# Use pivot_wider to change the dataframe to wide format
data_wide <- data %>% 
  pivot_wider(id_cols = category1, names_from = category2, values_from = value)

# Print the transformed dataset
print(data_wide)
482 chars
21 lines

In this example, category1 is used as the id column, category2 is used to create new column names, and value is used to fill the new columns. The resulting data_wide dataframe will have a wide format with category1 as the unique identifier and separate columns for each level of category2.

The output will look like this:

main.r
  category1  X  Y
1          A 10 20
2          B 30 40
3          C 50 60
75 chars
5 lines

related categories

gistlibby LogSnag