Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random Number generation for each row

Tags:

r

New to R coming from SAS...

I want to create a vector of 1,000 random numbers for each row using the function

runif(1,000, min = 0, max = 1) 

and add it to my data.frame.

Trying this gives me the same number on each row:

EL$randoms <- runif(1, min = 0, max = 1)  

How do I solve this simple problem?

like image 226
amerikashka Avatar asked Dec 15 '22 13:12

amerikashka


2 Answers

This way ?

EL$randoms <- runif(1000, min=0, max=1)

El$randoms is a whole column of your data frame. So you have to assign to it as many values as there are rows. With what you tried, only one random number was generated, and R, by its recycling rule, "repeats" it as many times as necessary to match the length of EL$randoms.

like image 200
juba Avatar answered Dec 29 '22 23:12

juba


Super late to this party, but it came up in a Google search. Here is a way to assign a random number for every row in the data set without having to specify the exact number of rows.

EL$randoms <- runif(nrow(EL), min = 0, max = 1)
like image 41
Ben Avatar answered Dec 29 '22 22:12

Ben