Download mixedL.csv (see “CSV format” under “Files used in the examples”) mixed_left <- read.csv('mixedL.csv') mixed_left First Last Age Group Veggie Fruit 1 John Sims 30 A Artichoke Apple 2 Mary Sims 25 A Asparagus Apricot 3 John Kent 40 A Avocado 4 John Sims 30 B Broccoli Banana 5 Mary Sims 25 B 6 John Kent 40 B Blueberry 7 John Sims 30 C Carrot Cherry 8 Mary Sims 25 C Celery Cranberry 9 John Kent 40 C Clementine Option 1: Transform using reshape Option 2: Transform using reshape2 library Option 3: Transform using tidyr library Option 1: Transform using reshape |
# From mixed_left to wide wide <- reshape(data = mixed_left, idvar = c('First','Last','Age'), timevar = 'Group', v.names = c('Veggie','Fruit'), direction = 'wide') wide First Last Age Veggie.A Fruit.A Veggie.B Fruit.B Veggie.C Fruit.C 1 John Sims 30 Artichoke Apple Broccoli Banana Carrot Cherry 2 Mary Sims 25 Asparagus Apricot Celery Cranberry 3 John Kent 40 Avocado Blueberry Clementine |
library(reshape2) # decast can only handle one value variable at a time, so we need to # melt the mixed format to long format first, and then cast it by # ‘Group’ and ‘Type’ to get the wide format # From mixed_left to wide temp <- melt(data = mixed_left, id.vars = c('First','Last','Age','Group'), measure.vars = c('Veggie','Fruit'), variable.name = 'Type', value.name = 'Plant') temp First Last Age Group Type Plant 1 John Sims 30 A Veggie Artichoke 2 Mary Sims 25 A Veggie Asparagus 3 John Kent 40 A Veggie 4 John Sims 30 B Veggie Broccoli 5 Mary Sims 25 B Veggie 6 John Kent 40 B Veggie 7 John Sims 30 C Veggie Carrot 8 Mary Sims 25 C Veggie Celery 9 John Kent 40 C Veggie 10 John Sims 30 A Fruit Apple 11 Mary Sims 25 A Fruit Apricot 12 John Kent 40 A Fruit Avocado 13 John Sims 30 B Fruit Banana 14 Mary Sims 25 B Fruit 15 John Kent 40 B Fruit Blueberry 16 John Sims 30 C Fruit Cherry 17 Mary Sims 25 C Fruit Cranberry 18 John Kent 40 C Fruit Clementine wide <- dcast(data = temp, formula = First+Last+Age~Group+Type, value.var = 'Plant') wide First Last Age A_Veggie A_Fruit B_Veggie B_Fruit C_Veggie C_Fruit 1 John Kent 40 Avocado Blueberry Clementine 2 John Sims 30 Artichoke Apple Broccoli Banana Carrot Cherry 3 Mary Sims 25 Asparagus Apricot Celery Cranberry
|
library(tidyr) # From mixed_left to wide wide <- mixed_left %>% gather(key = 'Type',value = 'Plant', Veggie:Fruit) %>% unite(col = 'key', Type, Group, sep='-') %>% spread(key = 'key', value = 'Plant') wide First Last Age Fruit-A Fruit-B Fruit-C Veggie-A Veggie-B Veggie-C 1 John Kent 40 Avocado Blueberry Clementine 2 John Sims 30 Apple Banana Cherry Artichoke Broccoli Carrot 3 Mary Sims 25 Apricot Cranberry Asparagus Celery |
Functions referenced:
reshape, names, gsub, cbind, rownames, order, paste
reshape2: dcast, melt, colsplit
tidyr: gather, separate, unite, spread
More information:
RStudio Data Wrangling Cheatsheet
--- The End ---