如何获取名称的data.frame从列表传递到函数使用lapply [英] how to get name of data.frame from list passed to function using lapply

查看:120
本文介绍了如何获取名称的data.frame从列表传递到函数使用lapply的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有能力将结果保存到csv文件中的功能。 csv文件的名称应根据传递给此函数的data.frame名称生成。

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"

但是我需要调用这个功能为每个data.frame从列表。如果我从列表中为特定的数据框架调用这个函数,那么它基本上是工作的(我得到的丑名也包含列表的名称,但是一个解决方法可以使用正则表达式修剪):

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"

问题当我想从列表中为所有data.frames调用此函数。在这种情况下,data.frame的名称是混乱的:

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?

推荐答案

列表中的每个数据框都被命名为

f each data frame in the list is named

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

在电话中原谅小错误

这篇关于如何获取名称的data.frame从列表传递到函数使用lapply的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆