Download long.csv (see “CSV format” under “Files used in the examples”) long <- read.csv('long.csv') long 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 Option 1: Transform using reshape Option 2: Transform using reshape2 library Option 3: Transform using tidyr library Option 1: Transform using reshape |
mixed_left <- reshape(long, idvar = c('First','Last','Age','Group'), timevar = 'Type', v.names = 'Plant', direction = 'wide') #Fix the names by removing the prefix from the data column names names(mixed_left) <- gsub('Plant.','',names(mixed_left)) 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 |
library(reshape2) mixed_left = dcast(data = long, formula = First + Last + Age + Group ~ Type, value.var = 'Plant', drop = TRUE) #Optional: sort data for easier comparison mixed_left[with(mixed_left,order(Group,Fruit)), ] First Last Age Group Fruit Veggie 4 John Sims 30 A Apple Artichoke 7 Mary Sims 25 A Apricot Asparagus 1 John Kent 40 A Avocado 8 Mary Sims 25 B 5 John Sims 30 B Banana Broccoli 2 John Kent 40 B Blueberry 6 John Sims 30 C Cherry Carrot 3 John Kent 40 C Clementine 9 Mary Sims 25 C Cranberry Celery |
library(tidyr) mixed_left <- long %>% spread(key = 'Type', value = 'Plant') #Optional: sort data for easier comparison library(plyr) arrange(mixed_left,Group, Fruit) First Last Age Group Fruit Veggie 1 John Sims 30 A Apple Artichoke 2 Mary Sims 25 A Apricot Asparagus 3 John Kent 40 A Avocado 4 Mary Sims 25 B 5 John Sims 30 B Banana Broccoli 6 John Kent 40 B Blueberry 7 John Sims 30 C Cherry Carrot 8 John Kent 40 C Clementine 9 Mary Sims 25 C Cranberry 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 ---