我构建了一个函数,其返回值根据其内容命名。使用 as.name()
在控制台中有效,但不能作为函数参数。
x <- "newNameforIris"
assign(x, iris)
as.name(x)
# [1] newNameforIris
head(newNameforIris) # gives familiar results (not included)
save(as.name(x), file = "nnfi.bin")
# [1] Error in save(as.name(x), file = "nnfi.bin") : object ‘as.name(x)’ not found
我也尝试了eval.promises = FALSE
,但没有成功。在函数执行之前我不知道对象的名称,因此我陷入困境,没有 as.name()
或替代方案。
最佳答案
我在提出这个问题2.5年后才发现这个问题,因为没有令人满意的答案,所以我调查了这个问题。这是我的发现。
调查:
重现失败,但问题不仅仅是 as.name()
。
x <- "newNameforIris"
assign(x, iris)
as.name(x)
head(newNameforIris) # as expected
save(as.name(x), file = "nnfi.bin")
# Error in save(as.name(x), file = NULL) : object ‘as.name(x)’ not found
save(as.character(x), file = "nnfi.bin")
# Error in save(as.character(x), file = NULL) : object ‘as.character(x)’ not found
save(eval(as.name(x)), file = "nnfi.bin")
# Error in save(eval(as.name(x)), file = "nnfi.bin") : object ‘eval(as.name(x))’ not found
以下成功。
y <- as.name(x)
save(y, file = "nnfi.bin")
save("x", file = "nnfi.bin")
save(list=c("x"), file = "nnfi.bin")
save(list=c(as.character(as.name(x))), file = "nnfi.bin")
结论:
save()
的 ...
参数只能接受符号和字符串,就像帮助文件中所说的“要保存的对象的名称” (作为符号或字符串)”。
那么让我们看看 save()
如何处理 ...
。只需输入 save
,而不是 save()
。
save
#....
# names <- as.character(substitute(list(...)))[-1L]
# list <- c(list, names)
#....
现在让我们使用 as.name(x)
以及上面其他失败的测试来测试它。
fx <- function(..., list = character()) {
names <- as.character(substitute(list(...)))[-1L]
list <- c(list, names)
return(list)
}
fx(as.name(x)) # [1] "as.name(x)"
fx(as.character(x)) # [1] "as.character(x)"
fx(eval(as.name(x))) # [1] "eval(as.name(x))"
答案:
save()
的 ...
参数中的项目不会被计算,而是转换为字符串,因此除非这些字符串与现有对象相同,函数调用将失败。
建议:
使用以下内容。
x <- as.name(x)
save(x, file = "nnfi.bin")
关于r - as.name() 不能作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34751636/