Reputation: 1845
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
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:
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()
)
)
Upvotes: 2
Views: 376
Reputation: 887691
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()
# ...
Upvotes: 1
Reputation:
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)
Upvotes: 3