Creating Random Samples From Entries in Neighboring Row

I am working with the R programming language.

I have the following data set:

my_data = data.frame(id = c(1,2,3,4,5), n = c(15,3,51,8,75))

I want to create a new variable that generates a single random integer for each row based on the corresponding value of "n". I tried to do this with the following code:

my_data$rand = sample.int(my_data$n,1)

But this is not working (the same random number is repeated 5 times).

I also tried to define a function to this:

my_function <- function(x){sample.int(x,1)}

transform(my_data, new_column= my_function(my_data$n) )

But this is also not working (the same random number is again repeated 5 times)..

In the end, I am trying to achieve something like this :

my_data$rand = c(sample.int(15,1), sample.int(3,1), sample.int(51,1), sample.int(8,1), sample.int(75,1))

Can someone please show me how to do this for larger datasets without having to manually specify each "sample.int" command?

Thanks!

Maybe this will work for you.

library(dplyr)

my_data = data.frame(id = c(1,2,3,4,5), n = c(15,3,51,8,75))
my_data <- my_data |> rowwise() |> mutate(rand=sample.int(n,1))
my_data
#> # A tibble: 5 x 3
#> # Rowwise: 
#>      id     n  rand
#>   <dbl> <dbl> <int>
#> 1     1    15     4
#> 2     2     3     2
#> 3     3    51    26
#> 4     4     8     5
#> 5     5    75    66

Created on 2022-06-03 by the reprex package (v2.0.1)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.