-1

Faced trouble using R trying to transform my dataset. The dataset is larger, with more food types, person IDs and "how often" options.

Please advice

fygeng go
  • 15
  • 4

1 Answers1

1

This type of transformation is called a "pivot". We are "pivoting" the data set from a long (many rows) format to a wide (many columns) format. This is easily done using the tidyr pivot_wider.

library(tidyr)
df_transformed<-df %>%
   pivot_wider(names_from="food_type", values_from="how_often")
Joe Erinjeri
  • 1,200
  • 1
  • 7
  • 15
  • Hi @Joe, thank you for your advice! I'm new to R, and after "pivoting" the dataset, I get a list of c(1, 3, 2) for person 1 under French food column. I was wondering how to create multiple rows instead of creating 1 row for each person containing all their "how often" points. – fygeng go Jan 17 '22 at 01:36
  • I understand the pivot_wider() creates list columns when there are any duplicated values, was wondering how to preserve the duplicated values – fygeng go Jan 17 '22 at 01:55
  • this is a little closer but still not exactly your output df_transformed<-df %>% mutate(id=row_number()) %>% relocate(id, .before=person) %>% pivot_wider(names_from="food_type", values_from="how_often") – Joe Erinjeri Jan 17 '22 at 03:10