参考参数而不评估它的R函数

R function with reference to argument without evaluating it

islands1<-islands #a named num (vector)

data.frame(island_col=names(islands1), number_col=islands1,row.names=NULL)

这将创建一个由两列组成的数据框,第一列包含命名向量中的名称并称为 "island_col",第二列包含数字并命名为 "number_col"。这里没问题。

现在假设我编写了一个函数,因为我有一堆这些命名向量正在转换为数据帧。每个向量都有编号,如 islands1、islands2 等

dfunc<-function(x) data.frame(island_col=names(x), as.name(x)<-(x),row.names=NULL) 这是一个使用 data.frame 将命名向量转换为数据帧

的函数

firstdf<-dfunc(islands) 我在 "islands1" 命名向量上使用该函数。我希望将数字列命名为 "islands1" 因为这是参数的名称,但 R 不理解这一点,而是尝试评估参数本身。我尝试了使用 paste0 函数和 as.character 的变体,但无法让它工作。

此外,是的,我知道导致这些命名向量的所有这些可能应该已经用 lapply 完成,所以我现在有一个列表可以使用。我花了很多时间走那条路(见我的另一个问题)但最终无法让它工作并且有最后期限要考虑。更一般地说,我试图更好地理解 R 如何以及何时评估参数以及如何索引对象。

尝试as.character(quote(islands1))

?quote: "quote simply returns its argument. The argument is not evaluated and can be any R expression."

I want number column to be named "islands1" because that's the name of the argument ...

使用deparsesubstitute如下

islands1 <- c(a = 1, b = 2, c = 3)
islands2 <- c(d = 3, e = 2, g = 1)

func <- function(x){
  out <- data.frame(island_col = names(x), xSym = x)
  names(out)[2] <- deparse(substitute(x))
  out
}

func(islands1)
#R   island_col islands1
#R a          a        1
#R b          b        2
#R c          c        3
func(islands2)
#R   island_col islands2
#R d          d        3
#R e          e        2
#R g          g        1