John Godlee - 6 months ago 26

R Question

I have a data frame:

`letter <- c("A", "B", "C")`

min <- c(1, 2, 3)

max <- c(4, 5, 6)

df <- data.frame(letter, min, max)

I want to add a 4th column to

`df`

`min`

`max`

I have an inkling that I should use

`sample()`

`df$random <- sample(df$max)`

Could I also use

`runif`

Answer

Assuming your dataframe `df`

as

```
letter min max
1 A 1 4
2 B 2 5
3 C 3 6
```

I have a feeling there should be a better base R solution than this. However, for now we can try with `apply`

and select (`sample`

) any random number between the two columns.

```
df$third_column <- apply(df, 1, function(x) sample(x[2]:x[3], 1))
df
# letter min max third_column
#1 A 1 4 1
#2 B 2 5 4
#3 C 3 6 4
```