r - as.name() 不能作为参数

标签 r rename

我构建了一个函数,其返回值根据其内容命名。使用 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/

相关文章:

Java:DOM 如何从名称列表中重命名节点名称

python - 重命名重构期间退格键、删除键和箭头键的行为

Linux/OS X 重命名保留时间戳

r - 在 .Rnw 中包含 rgl 交互图(pdf 输出)

r - 在 CentOS 的 fftwtools 上安装 R 包需要 fftw3

R:用最后一个非空单元格的值填充空单元格

c# - 当当前用户目录不同于 root 时,无法使用 ftp 方法重命名文件

r - 在R中,如何使函数内的变量可供该函数内的较低级别函数使用?(with、attach、environment)

r - 在R中绘制轴

r - 基于变量名称R的名称列表元素