-2

I am currently learning R programming, and I was tasked to generate a set of 20 two-digit random numbers. I know that I can paste sample(0:9, 2, replace=TRUE) in 20 lines, but I was wondering if there's a way to make a recurring function (like in Python) so that the code will be shorter. I searched how to create recurring functions in R, but I can't figure out how to count the generated numbers so that I can assign an if statement to terminate it. I would very much appreciate any help. Thank you!

star
  • 19
  • 3
  • 2
    You can't use `sample(10:99, 20)` ? – Ronak Shah Jul 10 '22 at 11:08
  • My professor wanted to see 00,01,02,03,04,... printed out as well so I thought I should print each digit individually since if I used ```sample(00:99, 20)``` the code still prints single digit numbers as single digits intead of with a zero – star Jul 10 '22 at 11:11
  • 2
    Then `sprintf("%02d", sample(1:99, 20))` ? – Joe Jul 10 '22 at 11:13

1 Answers1

1

You can use -

set.seed(2301)
sprintf('%02i', sample(99, 20))
#[1] "52" "93" "27" "01" "80" "37" "16" "83" "46" "32" "39" "57" "59" 
#    "26" "89" "75" "17" "70" "12" "90"

Or with two samples

set.seed(1422)
paste(sample(0:9, 20, replace = TRUE), sample(0:9, 20, replace = TRUE), sep = '')
#[1] "88" "71" "36" "01" "31" "92" "72" "61" "72" "39" "21" "03" "39" 
#    "74" "68" "87" "95" "92" "16" "34"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213