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
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.