rlistdataframeconstructcoerce

define R objects in a list based on column names in a dataframe


I have a data frame df with column names x1, x2, x3, etc.

df <- data.frame(x1 = rnorm(100), x2=rnorm(100),x3=rnorm(100))

I would like to create an R object that is a list that looks like:

my.list <- list(y, N = length(y),
                x1 = x1,
                x2 = x2,
                ...
                )

Where x1 -> xn are the colums of df.


Solution

  • I'll post it here so that the question can be marked as answered,

    dfL <- as.list(df)
    str(dfL)
    #> List of 3
    #>  $ x1: num [1:100] -0.0793 0.3049 -1.2734 -1.9316 -0.361 ...
    #>  $ x2: num [1:100] -0.302 0.277 1.131 -0.295 0.828 ...
    #>  $ x3: num [1:100] 0.486 1.73 -0.13 0.943 0.663 ...
    

    or

    require(dplyr)
    dfL <- df %>% as.list()
    

    or the minimal option, as suggested by Rich Scriven,

    dfL <- c(df)