【问题标题】:Function: return assigned argument instead of variable name功能:返回赋值参数而不是变量名
【发布时间】:2018-04-22 10:35:33
【问题描述】:

我搜索了很多,但没有找到任何问题的答案,尽管我确信它不应该那么困难。最接近的主题没有收到任何答案 (How do I access the name of the variable assigned to the result of a function within the function in R?)

无论如何,我正在尝试执行以下操作:该函数应创建两个对象,zdoc,并使用分配的名称而不是变量名称返回它。一个简短的例子:

fun.docmerge <- function(x, y, z, crit, typ, doc = checkmerge) {
  mergedat <- paste(deparse(substitute(x)), "+",
                    deparse(substitute(y)), "=", z)
  countdat <- nrow(x)
  check_t1 <- data.frame(mergedat, countdat)
  z <- join(x, y, by = crit, type = typ)
  countdat <- nrow(z)
  check_t2 <- data.frame(mergedat, countdat)
  doc <- rbind(doc, check_t1, check_t2)
  return(list(checkmerge = doc, z = z))
}

results <- fun.docmerge(x = df1, y = df2, z = "df3", crit = c("id"), typ = "left")

一些示例数据:

df1 <- structure(list(id = c("XXX1", "XXX2", "XXX3", 
"XXX4"), tr.isincode = c("ISIN1", "ISIN2", 
"ISIN3", "ISIN4")), .Names = c("id", "isin"
), row.names = c(NA, 4L), class = "data.frame")

df2 <- structure(list(id= c("XXX1", "XXX5"), wrong= c(1L, 
1L)), .Names = c("id", "wrong"), row.names = 1:2, class = "data.frame")

checkmerge <- structure(list(mergedat = structure(integer(0), .Label = character(0), class = "factor"), 
    countdat = numeric(0)), .Names = c("mergedat", "countdat"
), row.names = integer(0), class = "data.frame")

问题是这会将z 作为z 返回。但是,我希望它以df3(作为参数分配的名称)返回。有没有办法做到这一点?我可以轻松解决它以将doc 作为checkmerge 返回。但是,z 是动态的,所以这不起作用。

【问题讨论】:

  • 你能提供df1df2的例子吗?
  • 我添加了一个 reprod 示例
  • 只是一个提示:你正在做不寻常的事情,我觉得你的目标没有什么用处。但是,如果您想记录导致特定 data.frame 的连接,我建议将该信息存储在 data.frame 的属性中。
  • help("attr") 是您真正需要阅读的全部内容。
  • 我不知道你想做什么,特别是为什么你认为需要这个。在我看来,您似乎可以通过简单地阅读(并在必要时评论)您的脚本来获取所有信息。

标签: r


【解决方案1】:

试试这个

fun.docmerge <- function(x, y, z, crit, typ, doc = checkmerge) {
  mergedat <- paste(deparse(substitute(x)), "+",
                    deparse(substitute(y)), "=", z)
  countdat <- nrow(x)
  check_t1 <- data.frame(mergedat, countdat)
  z1 <- join(x, y, by = crit, type = typ)
  countdat <- nrow(z1)
  check_t2 <- data.frame(mergedat, countdat)
  doc <- rbind(doc, check_t1, check_t2)
  t1<-list()
  t1[["checkmerge"]]<-doc
  t1[[z]]<-z1
  return(t1)
}

【讨论】:

  • 谢谢!但是当通过results &lt;- fun.docmerge(x = df1, y = df2, z = "df3", crit = c("id"), typ = "left") 调用这个函数时,我得到Error in temp[[checkmerge]] &lt;- doc : invalid subscript type 'list'
  • 已更新。如果 checkmerge 不是变量,则只需将其放在引号中。如果您可以提供工作集,我们可以提供帮助。我从你的问题中了解到,你想把变量值作为变量名。为了做到这一点 t[[x]]
  • 谢谢,但还是一样。我在问题中添加了示例数据,如果您定义函数、定义数据并评估函数,就像我的评论中一样,您会收到错误消息,以及更新后的函数。
  • 是加入还是合并?你正在使用哪些软件包,我在尝试加载它时遇到错误
  • 现在检查更新的代码,但您的要求似乎很奇怪:)。无论如何,我会把它留给你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-27
  • 2019-01-30
  • 2019-11-07
  • 1970-01-01
  • 2012-02-05
  • 1970-01-01
相关资源
最近更新 更多