use pivot_wider to change only some columns to wide format and keep others in long format in r

You can specify the columns you want to keep in long format by including them in the values_from argument of pivot_wider function. Here's an example:

library(tidyr)

# Sample data frame
df <- data.frame(
  id = c(1, 1, 2, 2),
  name = c("Alice", "Alice", "Bob", "Bob"),
  attribute = c("height", "weight", "height", "weight"),
  value = c(160, 130, 180, 150)
)

# Using pivot_wider to spread only the 'value' column
result <- df %>%
  pivot_wider(
    id_cols = id:name,
    names_from = attribute,
    values_from = value
  )

# Displaying the result
print(result)
416 chars
21 lines

In this code snippet, only the 'value' column is pivoted from long to wide format while 'id' and 'name' columns are kept in long format.

related categories

gistlibby LogSnag