Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-liner to create a data.frame and have columns depend on each other

Tags:

dataframe

r

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)

y vs x

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.

like image 798
Ari B. Friedman Avatar asked Dec 18 '25 07:12

Ari B. Friedman


1 Answers

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).

like image 176
Sven Hohenstein Avatar answered Dec 19 '25 22:12

Sven Hohenstein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!