2

I want create an empty list which takes on the name of a dataframe and has empty elements inside based on the name of the dataframe

What I've Tried - Does Not Work

my_list_function <- function(thedata) {
  list(
    x = map(names(x), ~ .x = list())
  ))
}

I want to be able to run

my_list_function(mtcars)

and get the output:

Desired Output

list(
  mtcars = list(
    mpg = list(),
    cyl = list(),
    disp = list(),
    hp = list(),
    drat = list(),
    wt = list(),
    qseq = list(),
    vs = list(),
    am = list(),
    gear = list(),
    carb = list()
  )
)
0

2 Answers 2

3

Using purrr:

library(purrr)
map(mtcars, ~ list())

If you want the name of the data itself in the list, you can try this:

my_list_function <- function(data) {
  .data <- rlang::enquo(data)

  list(map(data, ~ list())) %>% 
    set_names(rlang::as_name(.data))
}

my_list_function(mtcars)
Sign up to request clarification or add additional context in comments.

Comments

1

We can use setNames

my_list_function <- function(data) {
     nm1 <- deparse(substitute(data))
    setNames(list( setNames(rep(list(list()), length(data)), names(data))), nm1)
      }

my_list_function(mtcars)
#$mtcars
#$mtcars$mpg
#list()

#$mtcars$cyl
#list()

#$mtcars$disp
#list()

#$mtcars$hp
#list()
# ...

Or using purrr

library(purrr)
library(dplyr)
my_list_function <- function(data) {


   lst(!! enquo(data) := map(data, ~ list()))
  }
my_list_function(mtcars)
#$mtcars
#$mtcars$mpg
#list()

#$mtcars$cyl
#list()

#$mtcars$disp
#list()

#$mtcars$hp
#list()
# ...

3 Comments

Typo with "lst" in the purrr answer. And I don't know if it is an rlang version thing or something but I get Error: :=` can only be used within a quasiquoted argument` as well (I had it in my solution at first and then it stopped working).
@Adam sorry, lst is found in both tibble and dplyr. I should have updated it
Great. Works now. Good to know, that was effectively what I wanted to do but settled for set_names().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.