0

I am not a very specialist R programmer and I would like to have and advice on how to retrieve the maximum value in a certain column for each unique row.

Let's make a simple example of the dataframe that i have:

   `fruit`   `dessert                difficulty`

1  `apple    cinnamon and apple`         0

2  `apple`     `apple-pie`              `1`

3  `apple`     `strudel`                `2`

4  `banana`    `banana-split`           `0`

5  `banana`    `banana-pie`             `1`

6  `banana`    `banana pancakes`        `2`

7  `banana`    `banana ice-cream`       `3`

For each row i want to take the maximum 'difficulty' of each fruit (e.g. apple = 2) and use this value for other function. In my real dataframe I don't know the exact name of the fruit values, but I know that they are repeated like in this example.

My idea was to perform a for loop, but i guess there is an easiest way to perform it.

Thanks in advance!

Claudio21
  • 45
  • 5

1 Answers1

0

Maybe you want ave

df <- within(df,difficulty_max <- ave(difficulty,fruit,FUN = max))

such that

> dfout
   fruit            dessert difficulty difficulty_max
1  apple cinnamon and apple          0              2
2  apple          apple-pie          1              2
3  apple            strudel          2              2
4 banana       banana-split          0              3
5 banana         banana-pie          1              3
6 banana    banana pancakes          2              3
7 banana   banana ice-cream          3              3
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81