问题
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