[英]How to create new variables with information from 2 categorical and 1 numeric variable
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. 我想使用变量Food,Meal和Amount中的信息来创建几个新变量,因此一行上只有一个ID。 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. 因此,我将使用诸如Cereal_BF,Cereal_Lunch,Cereal_Dinner,Meat_BF,Meat_Lunch,Meat_Dinner,Potato_BF,Potato_Lunch,Potato_Dinner等变量,这些变量显示来自变量Amount的对应信息。
Thank you for your help! 谢谢您的帮助!
Patricia 帕特里夏
You can combine columuns and spread them using tidyverse
functions. 您可以合并列,并使用tidyverse
函数传播它们。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.