0

I have a data set looking like this:

ID  Meal    Food    Amount
1   Lunch   Meat    50
1   Lunch   Potato  10
1   Dinner  Fish    105
1   Dinner  Rice    100
1   Dinner  Pulses  50
2   BF     Cereal   100
2   BF      Milk    200
2   Lunch   Rice    200
2   Lunch   Chicken 150
2   Lunch   Veg     100
2   Dinner  Pasta   200
2   Dinner  Meat    200
2   Dinner  Tomato  50
2   Dinner  Cheese  10

I would like to use the information in the variables Food, Meal and Amount to create several new variables and thus only have one ID on one row. Hence, I would have variables like Cereal_BF, Cereal_Lunch, Cereal_Dinner, Meat_BF, Meat_Lunch, Meat_Dinner, Potato_BF, Potato_Lunch, Potato_Dinner etc. that show the coorresponding information from the variable Amount.

Thank you for your help!

Patricia

leeum
  • 264
  • 1
  • 13
  • 1
    Possible duplicate of [Paste multiple columns together](https://stackoverflow.com/questions/14568662/paste-multiple-columns-together) – pogibas Jan 25 '18 at 14:41

1 Answers1

0

You can combine columuns and spread them using tidyverse functions.

dd %>% 
   unite(MealFood, Meal, Food) %>% 
   spread(MealFood, Amount)

where

dd<-read.table(text="ID  Meal    Food    Amount
1   Lunch   Meat    50
               1   Lunch   Potato  10
               1   Dinner  Fish    105
               1   Dinner  Rice    100
               1   Dinner  Pulses  50
               2   BF     Cereal   100
               2   BF      Milk    200
               2   Lunch   Rice    200
               2   Lunch   Chicken 150
               2   Lunch   Veg     100
               2   Dinner  Pasta   200
               2   Dinner  Meat    200
               2   Dinner  Tomato  50
               2   Dinner  Cheese  10", header=T, stringsAsFactors=F)
MrFlick
  • 195,160
  • 17
  • 277
  • 295