0

Usecase:

when exporting excel sheets with different datasets you would naturally pass them through a list so that you modulise your code and not to do reptitive work. To get tab names you need to convert those object names into a vector of strings. Imaging when you have so many of them

# so you know the datasets here

list_data <- list(
mtcars,
cars,
Seatbelts,
UKDriverDeaths
)

# the output should be
c(
"mtcars",
"cars",
"Seatbelts",
"UKDriverDeaths"
)

# tested this and it worked but I cannot modulise it for some reason

library(tidyverse)


# prepare data ----
list_data <- list(
    mtcars,
    cars,
    Seatbelts,
    UKDriverDeaths
)



# this gets a good output but not sure why I cannot convert it into a function
list_sheets <- list(mtcars,
                    cars,
                    Seatbelts,
                    UKDriverDeaths) |>
    
    quote() |>
    # print() |>
    as.character() |>
    tibble(list_sheets=_) |>
    slice(-1) |>
    pull()

# trying to do a function
parse_sheet_names <- function(x){
    x |>
        quote() |>
        print() |>
        as.character() |>
        tibble(list_sheets=_) |>
        slice(-1) |>
        pull()
}

# testing the function
list(mtcars,
     cars,
     Seatbelts,
     UKDriverDeaths) |>
    parse_sheet_names()

list_data |>
    map(~parse_sheet_names)

r2evans
  • 141,215
  • 6
  • 77
  • 149
Ahmad I
  • 11
  • 1
  • 3
    What is the problem? – Mark Aug 25 '23 at 18:17
  • Once your list `list_data` is formed, there is no way to (confidently/safely) reconstitute the objects' names from which the data was derived. If you want the names to persist, one option is to use `tibble::lst` in place of `list`, it retains the object name as `names(list_data)`. Another option is to set the names when you create it, as in `list(mtcars=mtcars, cars=cars, quux=Seatbelts)` (names do not need to match, of course). A third option is `setNames(list(...), c("mtcars", ...))` or to set the names later using `names(list_data) <- c("mtcars", ...)`. – r2evans Aug 25 '23 at 20:40
  • Thank you for this r2evans. This works. never knew about tibble::lst(iris,mtcars) |> names() – Ahmad I Aug 27 '23 at 04:53

0 Answers0