A not-uncommon situation in generating data.frames (particularly for SO questions which are not reproducible) is when one column depends on the (typically random) values of another. For instance, if one wants a data.frame to test regression on, it would be great to have some noisy linear dependence:
n <- 100
x <- runif(n)
dat <- data.frame( x=x, y=x+runif(n) )
plot(y~x,data=dat)

However, I'd like to do it in one line (the above would count as two lines, the first creating x, the second using x in the data.frame assignment), ideally without depositing anything in the global environment.
Here's an easy solution with within:
within(data.frame(x = runif(n)), y <- x + runif(n))
This command does not assign y to the global environment (or parent frame).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With