功能:返回分配的参数而不是变量名

时间:2017-11-09 12:22:06

标签: r

我搜索了很多,但没有找到任何问题的答案,即使我确信它不应该那么困难。最接近的线程没有得到答案(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是动态的,所以这不起作用。

1 个答案:

答案 0 :(得分:3)

试试这个

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)
}
相关问题