R代码:如何在循环内使用函数'assign'将属性设置为n个对象

问题描述 投票:1回答:1

我在将属性设置为从列表中获取的n个对象时遇到问题,尝试类似操作会导致错误:

N = 3#或我感兴趣的列表中的任何数字。

for (i in 1:N){

assign(paste0("obj",i),unlist(list[i],recursive=F,use.names=T))     #works great

attr(paste0("obj",i),'ID') <-'name'                                 #this is the issue 

}

给我一个错误“赋值目标扩展为非语言对象”

我试图通过使用类似这样的方法来解决这个问题:

tmp<-paste0("obj",i)
parse(file="", text=tmp)$'ID'<-'name'

以及多种变体而没有成功。我什至从包“ Bit”中尝试了功能“ setattr”。有谁知道我该怎么解决?

r loops assign
1个回答
0
投票

只需先分配属性:

mylist <- list(1:3, letters, rnorm(5))

for (i in seq_along(mylist))
{
  new_object <- unlist(mylist[i], recursive = FALSE, use.names = TRUE)
  attr(new_object, "ID") <- "name"
  assign(paste0("obj", i), new_object)
}

obj1
#> [1] 1 2 3
#> attr(,"ID")
#> [1] "name"
obj2
#>  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
#> [20] "t" "u" "v" "w" "x" "y" "z"
#> attr(,"ID")
#> [1] "name"
obj3
#> [1] -1.296529567  0.932548362 -0.935856164  0.002168237  0.024290270
#> attr(,"ID")
#> [1] "name"
© www.soinside.com 2019 - 2024. All rights reserved.