在 R 中,如何在一行中设置对象的名称和 return?

In R, how can I set the names of an object and return it in one line?

我想在一行中设置我的 R 对象和 return 的名称。它应该看起来像:

names(doWork(), c("a", "b", "c"))

并执行相当于:

x <- doWork()

names(x) <- c("a", "b", "c")

x

这可能吗?

你可以试试setNames

x <- setNames(doWork(), letters[1:3])

添加@rawr 声明的内容:

`names<-`(x, letters[1:3])

有效。这对于设置名称来说不是很有趣,因为 setNames 存在,但是还有许多其他属性替换函数没有相应的属性设置函数,所以这可能会很有用(打代码高尔夫时)。例如,如果我们要为矩阵列表设置列名:

mats <- replicate(2, matrix(sample(1:100, 4), 2), simplify=F) # list of matrices
lapply(mats, `colnames<-`, LETTERS[1:2])

生产:

[[1]]
      A  B
[1,] 78 59
[2,] 39 93

[[2]]
      A  B
[1,] 99 54
[2,]  1 16