R 代码:如何在循环中使用函数 'assign' 将属性设置为 n 个对象
R Code: how to use function 'assign' inside a loop to set attributes to n number of objects
我在将属性设置为从列表中获取的 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
}
给我一个错误 "target of assignment expands to non-language object"
我试图通过使用这样的方法来解决这个问题:
tmp<-paste0("obj",i)
parse(file="", text=tmp)$'ID'<-'name'
和多个变体都没有成功。我什至尝试了包 'Bit' 中的函数 'setattr'。有谁知道我该如何解决这个问题?
先给属性赋值:
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"
我在将属性设置为从列表中获取的 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
}
给我一个错误 "target of assignment expands to non-language object"
我试图通过使用这样的方法来解决这个问题:
tmp<-paste0("obj",i)
parse(file="", text=tmp)$'ID'<-'name'
和多个变体都没有成功。我什至尝试了包 'Bit' 中的函数 'setattr'。有谁知道我该如何解决这个问题?
先给属性赋值:
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"