3
votes

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?

3
What exactly is the output you're after? A data.frame with 1000 columns? - Roman Luštrik
um... @Julius, I think you may have corrected the mistake in OP's question by removing the , in runif(1,000...).. not sure though. - Arun
@joe, what's the problem with your first command? It gives you 1000 uniformly generated values... - Arun
Well, if you mix the first and the second line of code, you get the solution. But the second line of code is wrong, as only one value is assigned to a vector... - juba
@Arun, it might be so, I put , back to make sure. - Julius Vainora

3 Answers

6
votes

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.

4
votes

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)
1
votes

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

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