Home > database >  Add 1 to a random value in a column using dplyr
Add 1 to a random value in a column using dplyr

Time:08-19

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.

CodePudding user response:

Try this:

Colours_and_numbers %>% 
  mutate(
    numbers = numbers   sample(c(rep(0, n()-1), 1), n(), F)
  )

Reprex with some dummy data:

set.seed(1)
library(dplyr, warn.conflicts = F)
tibble(numbers = 1:10) %>% 
  mutate(
    numbers = numbers   sample(c(rep(0, n()-1), 1), n(), F)
  )
#> # A tibble: 10 x 1
#>    numbers
#>      <dbl>
#>  1       1
#>  2       2
#>  3       3
#>  4       4
#>  5       5
#>  6       6
#>  7       7
#>  8       9
#>  9       9
#> 10      10

Created on 2022-08-18 by the reprex package (v2.0.1)

CodePudding user response:

You could use ifelse so that there is no need to refer to the sampling number twice.

Colours_and_numbers %>% 
  mutate(res = ifelse(1:n() == sample(n(), 1), numbers 1, numbers))

#    colours numbers res
# 1   Yellow       7   7
# 2      Red      19  19
# 3   Orange       8   8
# 4     Blue      10  10
# 5    Green       5   5
# 6    Black       9   9
# 7   Purple       9  10 <here>
# 8    White      13  13
# 9     Grey      11  11
# 10   Brown       9   9
Data
Colours_and_numbers <- structure(list(
  colours = c("Yellow", "Red", "Orange", "Blue", "Green", "Black", "Purple", "White", "Grey", "Brown"),
  numbers = c(7L, 19L, 8L, 10L, 5L, 9L, 9L, 13L, 11L, 9L)),
  class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"))

CodePudding user response:

If you want to append a randomly selected row to an existing table, you can sample the row index and bind the rows.

Colours_and_numbers %>% dplyr::bind_rows(.[sample(nrow(.), 1),])

CodePudding user response:

Simpler with magrittr base R:

library(magrittr)

row <- sample(nrow(Colours_and_numbers), 1L)
Colours_and_numbers[row, "numbers"] %<>% add(1L)
  • Related