How to get name data.frame from list passed to function using lapply

I have a function that I want to expand with the ability to save the results to a csv file. The csv file name should be generated based on the data.frame name passed to this function:

my.func1 <- function(dframe, ...){
  # PART OF CODE RESPONSIBLE FOR COMPUTATION
  # ...

  # PART OF CODE WHERE I WANT TO STORE RESULTS AS CSV
  csv <- deparse(substitute(dframe))
  csv
}

When I call this function as follows, the dataset name passed to this function is interpreted correctly:

> my.func1(mtcars)
[1] "mtcars"

But I need to call this function for each data.frame file from the list. If I call this function for a specific data.frame from a list, it basically works (I get an ugly name that also contains the name of the list, but one workaround can trim it with a regular expression):

> LoDFs <- list(first=data.frame(y1=c(1,2,3), y2=c(4,5,6)), second=data.frame(yA=c(1,2,3), yB=c(4,5,6)))
> my.func1(LoDFs$first)
[1] "LoDFs$first"

The problem is when I want to call this function for all data.frames from the list. In this case, the data.frame names are messy:

> lapply(LoDFs, my.func1)
$first
[1] "X[[i]]"

$second
[1] "X[[i]]"

> lapply(seq_along(LoDFs), function(x) { my.func1(LoDFs[[x]]) })
[[1]]
[1] "LoDFs[[x]]"

[[2]]
[1] "LoDFs[[x]]"

?

+4
2

f

lapply (names (LoDf),function(i)write.csv (my.fun1 (LoDf [[i]]),paste0 (i,'.csv')))

+3

, lapply , .

mapply, ,

mapply(function(L,N){write.csv(L, paste0(N,".csv"));}, L=LoDFs,N=names(LoDFs))
+2

All Articles