Custom transpose of data frame

Hi. I have a data frame that somehow looks like this:

How do you do this in R?

Thank you.

Hey @hlhizon , you can reshape that kind of data easily using mutate(), row_number(), and pivot_wider().

Working example:

pacman::p_load(tidyverse)

# Example data
df <- data.frame(
  ID = c(1,1,1,2,2,3,3,3,3),
  Area = c("A","B","C","D","E","F","G","H","I")
)

# Transform to wide format
df_wide <- df %>%
  group_by(ID) %>%
  mutate(area_num = row_number()) %>%   # give each Area an index within ID
  pivot_wider(
    names_from = area_num,
    values_from = Area,
    names_prefix = "Area"
  )

df_wide

row_number() automatically numbers each Area within an ID and pivot_wider() spreads those numbered values into columns (Area1, Area2, …). Keep in mind that missing positions are filled with NA.

Hope this is clear,

Best

Luis

This is very helpful… thank you so much Luis…

1 Like