Using get() with replacement functions

前端 未结 2 894
野的像风
野的像风 2020-11-29 12:04

Can anyone explain to me why the following example occurs?

#Create simple dataframe
assign( \"df\" , data.frame( P = runif(5) , Q = runif(5) , R = runif(5) )         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 12:53

    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
    

提交回复
热议问题