Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have function which I want to extend with ability to save results to csv file. The name of csv file should be generated based on 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 following way then the name of dataset passed to this function is interpreted correctly:

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

But I need to call this function for each data.frame from list. If I call this function for particular data.frame from list then it is basically working (I get the ugly name containing also name of list but one workaround could be trim it using 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"

Problem is when I want to call this function for all data.frames from list. In this case the names of data.frame are mess:

> 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]]"

What I'm doing wrong and how can I avoid mentioned workaround with regular expressions and make code more robust?

like image 518
Wakan Tanka Avatar asked Mar 30 '16 21:03

Wakan Tanka


1 Answers

f each data frame in the list is named

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

On phone so forgive small mistakes

like image 135
Carl Boneri Avatar answered Sep 24 '22 13:09

Carl Boneri