我有一个数据帧,看起来像我需要通过组基于共同的ID来转以下工作:如何通过组列标题转数据帧中的R
testDF = data.frame(c("Id", "1", "1", "2", "2"), c("Item", 'Milk','Eggs','Bacon', "Bread"))
testDF
#>Id Item
#>1 Milk
#>1 Eggs
#>2 Bacon
#>2 Bread
newDT <- dcast(testDF, Id ~ Item, value.var = "Item")
View(newDT)
我需要的输出到如下所示(完全不包括标题行和Id列):
Milk, Eggs (Id 1)
Bacon, Bread (Id 2)
我收到错误“错误:value.var(项目)在输入未找到”。你能告诉我我做错了什么吗?
谢谢, 马特
对于列表,请使用'split(testDF $ Item,testDF $ Id)'。这是一个非常灵活的对象。对于一个不太灵活的对象作为data.frame可能这个职位:[http://stackoverflow.com/questions/16596515/aggregating-by-unique-identifier-and-concatenating-related-values-into-a-string]( http://stackoverflow.com/questions/16596515/aggregating-by-unique-identifier-and-concatenating-related-values-into-a-string)。 – lmo
您的意思是:testDF = data.frame(Id = c(“1”,“1”,“2”,“2”),Item =('Milk','Eggs','Bacon','Bread' ))? – maller
当我使用代码:result < - aggregate(Item〜Id,data = testDF,paste,collapse =“,”)我收到错误“eval(expr,envir,enclos)中的错误:object'Item'not发现”。有没有理由不承认“项目”? –