0

I need to use the R 'table' command across two columns of a dataframe. The results should be saved back to the dataframe. Say, I have the following df:

df <- data.frame(Day = c('2023-07-01', '2023-07-01', '2023-07-01', '2023-07-01', '2023-07-02', '2023-07-02', '2023-07-02', '2023-07-03'),
                 Vegetable = c('Apple', 'Pear', 'Potato', 'Apple', 'Pear', 'Pear', 'Apple', 'Tomato'))
                 
> df
         Day Vegetable
1 2023-07-01     Apple
2 2023-07-01      Pear
3 2023-07-01    Potato
4 2023-07-01     Apple
5 2023-07-02      Pear
6 2023-07-02      Pear
7 2023-07-02     Apple
8 2023-07-03    Tomato

Now, I would need to calculate the total of each vegetable per day and put it back to df. Basically, I would need this kind of output:

> df
         Day Vegetable table
1 2023-07-01     Apple   2
2 2023-07-01      Pear   1   
3 2023-07-01    Potato   1
4 2023-07-01     Apple   2
5 2023-07-02      Pear   2
6 2023-07-02      Pear   2
7 2023-07-02     Apple   1
8 2023-07-03    Tomato   1
             

Is there any command I could use? Thanks in advance.

Arturo
  • 342
  • 1
  • 4
  • 14

0 Answers0