gpt4 book ai didi

r - 函数 : return assigned argument instead of variable name

转载 作者:行者123 更新时间:2023-12-01 13:28:32 24 4
gpt4 key购买 nike

我搜索了很多但没有找到我的问题的任何答案,尽管我确信它不应该那么困难。最接近的线程未收到任何答复 ( 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 是动态的,所以这行不通。

最佳答案

试试这个

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)
}

关于r - 函数 : return assigned argument instead of variable name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47201750/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com