Create random numbers in R

Beginner sort

I had to generate a random numbers list of n=100. This is how I achieved it in R.

Soundarya Soundararajan true
2022-01-04

To create a random numbers list and write the output in excel, this is how you would proceed, step by step.

#generate unique random integers in R for Excel

Library loading

I need to sample 100 numbers from 1:10,000

Sample

sample(1:10000, 100, rep = FALSE)
  [1] 5986 6247 7618  387 5884  751 1070 1651 9462 2030 6290 3221 6582
 [14] 2034 6579 2602 4490 1440 3475  803 2482 8392 5014 1657 8120 5311
 [27] 7962 2128 2330 6149 9940 2967 9231 5779 4335 9147 6804 9718 8550
 [40] 4820 9104 8558 7717  875 1093 3622 6024 4504 1513 1947 4384 7387
 [53] 5139 7743 5898 5026 8207 5149 7103 1852 7707  734  634 6477 7331
 [66] 6693 8140 3608 3278 2817 3911 9777  259 7576 9037 1470 8040  376
 [79] 2543 5243 3285 5850 1979  116  981 6239 1903 1101 3887  861 2492
 [92] 6366 1437 7396 3597 3690 8591 4419  701 9164

Let’s store it in an object, “x”

Storing the sample

x <- sample(1:10000, 100, 
            rep = FALSE) #you can set replace as true according to your needs, i do not want overlaps, so i have chosen replace as false

If you want, you can check x

Sort and save as excel

x <- sort(x)# I want the list to be arranged for easy downstream works, feel free to skip this if you are not particular about arranging the numbers
x <- data.frame(x)
#write_xlsx(x, "listofnumbers.xlsx") #To export this list of numbers to excel

That’s all, Happy sampling!

Citation

For attribution, please cite this work as

Soundararajan (2022, Jan. 4). My R Space: Create random numbers in R. Retrieved from https://github.com/soundarya24/SoundBlog/posts/2022-01-04-create-random-numbers-in-r/

BibTeX citation

@misc{soundararajan2022create,
  author = {Soundararajan, Soundarya},
  title = {My R Space: Create random numbers in R},
  url = {https://github.com/soundarya24/SoundBlog/posts/2022-01-04-create-random-numbers-in-r/},
  year = {2022}
}