Search code examples
rrlang

Data frame creation with dynamically assigned variable names


I'd like to assign a value to a variable the name of which is determined on the fly, and then assign that variable to a column of a data frame, something like:

x = rnorm(10)
y = 'z'
data.frame(assign(y, x))

While assign(y, x) creates z with the right values, it fails to name the data frame's column "z".


Solution

  • Based on the OP comment, the solution would be:

    #Code
    assign(y, x)
    

    For the other issue you can try:

    #Code2
    df <- data.frame(assign(y, x))
    names(df)[1] <- y
    

    Output:

    df
                z
    1  -0.5611014
    2  -2.2370362
    3   0.9037152
    4  -1.1543826
    5   0.4997336
    6  -0.4726948
    7  -0.6566381
    8   1.0173725
    9  -0.5230326
    10 -0.9362808