amerikashka
amerikashka

Reputation: 173

Random Number generation for each row

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?

Upvotes: 5

Views: 18014

Answers (3)

Andrew Brēza
Andrew Brēza

Reputation: 8317

Here's the obligatory tidyverse answer using the popular newer syntax:

mtcars %>% 
    add_column(runif = runif(nrow(.)))

Upvotes: 6

Ben
Ben

Reputation: 175

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)

Upvotes: 6

juba
juba

Reputation: 49053

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.

Upvotes: 6

Related Questions