Using get() with replacement functions

五迷三道 提交于 2019-11-27 02:09:18
hadley

To understand why this doesn't work, you need to understand what colnames<- does. Like every function in that looks like it's modifying an object, it's actually modifying a copy, so conceptually colnames(x) <- y gets expanded to:

copy <- x
colnames(copy) <- y
x <- copy

which can be written a little more compactly if you call the replacement operator in the usual way:

x <- `colnames<-`(x, y)

So your example becomes

get("x") <- `colnames<-`(get("x"), y)

The right side is valid R, but the command as a whole is not, because you can't assign something to the result of a function:

x <- 1
get("x") <- 2
# Error in get("x") <- 2 : 
#  target of assignment expands to non-language object

Using assign in the way you demonstrate in the question is at least uncommon in R. Normally you would just put all objects in a list.

So, instead of

for (i in 1:10) {
assign( paste( "Object" , i , sep = "." ) , rnorm(1000 , i) )}

you would do

objects <- list()
for (i in 1:10) {
objects[[i]] <- rnorm(1000 , i) }

In fact, this construct is so common that there is a (optimized) function (lapply), which does something similar:

objects <- lapply(1:10, function(x) rnorm(1000,x))

You can then access, e.g., the first object as objects[[1]] and there are several functions for working with lists.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!