jeudi 18 août 2022

Add 1 to a random value in a column using dplyr

I have the following dataframe, in tibble format:

> Colours_and_numbers

# A tibble: 10 × 2
   colours numbers
   <chr>     <dbl>
 1 Yellow        7
 2 Red          19
 3 Orange        8
 4 Blue         10
 5 Green         5
 6 Black         9
 7 Purple        9
 8 White        13
 9 Grey         11
10 Brown         9

I would like to add 1 to a randomly chosen row from the numbers column using dplyr. For that purpose I tried using

Colours_and_numbers %>% 
   mutate(colours = replace(colours, sample((1:10), 1), colours[sample((1:10), 1)] + 1))

However, this is not working, as first sample() and second sample() will hardly ever refer to the same element of the numbers column.

Is there a way I can make sure both sample() refer to the same element without creating a specific variable to store the value generated by the first sample() and then using it in the last part of the replace() function? If you come up with a simpler way to add 1 to a random row, it would also appreciate that.




Aucun commentaire:

Enregistrer un commentaire