0

Let's say, for the sake of the example, that I have a list of departments. Everyone of them is on a separate table named "departmentName", so I created a list this way.

depts <- c("financial","sales",.....)

and then iterate to get members this way creating a function:

get.employees <- function(tablename) {

  con <- DBI::dbConnect(connectiondata....)

  query <- glue::glue("select name,position,area from {tablename}")

  assign(tablename,
         dplyr::tbl(conn, sql(query)) %>% collect())

}

lapply(depts,get.employees)

It works fine but It returned a list of data frames with no name assigned to every element as I was expecting.

I need every dataframe named as the department name.

2
  • 1
    lapply(setNames(nm = depts), get.employees) Commented Apr 12, 2019 at 12:27
  • if you do result <- lapply(depts,get.employees) than names(results) <- depts should assigne the names Commented Apr 12, 2019 at 12:27

2 Answers 2

1

1) Simplifying the example to use get.employees and depts in the Note at the end we can use Map instead of lapply:

L <- Map(get.employees, depts)
names(L)
## [1] "finance" "sales"  

2) This also works:

L2 <- sapply(depts, get.employees, simplify = FALSE)
names(L2)
## [1] "finance" "sales"  

Note

Simplified example:

get.employees <- function(x) BOD
depts <- c("finance", "sales")
Sign up to request clarification or add additional context in comments.

Comments

0

You can also try-

> ls <- mapply(get.employees, depts,SIMPLIFY = F)

> names(ls)
[1] "finance" "sales" 

Note- Input data was taken from answer provided by @G. Grothendleck

Comments

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.