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

不想你离开。 提交于 2019-12-10 14:24:10

问题


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?


回答1:


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




回答2:


The issue is that lapply does not feed the name of the item in the list, it only feed the item itself.

An alternative solution is to use mapply which IMO is more specific about the input rather than relying on scoping

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


来源:https://stackoverflow.com/questions/36320460/how-to-get-name-of-data-frame-from-list-passed-to-function-using-lapply

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!