How do you combine two data frames with quantities of items in R?

南笙酒味 提交于 2021-01-28 23:14:18

问题


I am working in R using data frame containing quantities of items (which are non-negative integers). Here is an example of two data frames called BASKET1 and BASKET2. In both cases, an item appears in the data frame only if it has a quantity of at least one. Items appear in each data frame in alphabetical order.

BASKET1
    Vegetable  Quantity
1     Carrots         3
2   Cucumbers         2
3    Parsnips         5
4      Celery         1
5      Onions        12

BASKET2
    Vegetable  Quantity
1     Carrots        10
2      Onions         6
3     Rhubarb         2

I am trying to create a function that combines two baskets of items into a single basket, adding up all of the items in both baskets. This is a kind of merge operation, except that I actually want to sum the quantities in the baskets. It is quite simple to obtain the list of items by using the unique function:

VEGETABLES <- unique(BASKET1$Vegetable, BASKET2$Vegetable);

I am having more difficulty finding a simple way to get the vector of quantities corresponding to this vector of items, to build the data frame of the combined baskets. I think there is a way to do this using some kind of simple lookup query, but all the methods I have tried lead to code that is cumbersome.


Question: What is the simplest way to find the vector of quantities corresponding to the combined vector of items?


回答1:


We can use rbind to rbind the two datasets and aggregate to get the sum of 'Quantity' by 'Vegetable

aggregate(Quantity ~ Vegetable, rbind(BASKET1,BASKET2), sum)


来源:https://stackoverflow.com/questions/60480792/how-do-you-combine-two-data-frames-with-quantities-of-items-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!