简体   繁体   中英

Append function that assign new value

I am trying to create a function Append that does not return a value but directly extend the first variable. Currently, to append y to x I do

x = append(x,y)

I would like to be able to do

Append(x,y)

and get the same result. I first thought of something like

Append = function(a,b,VarName) assign(VarName,append(a,b), envir = .GlobalEnv)
Append(x,y,"x")

It works but it is quite unsatisfying to have to pass the name of the original variable. Is there a better solution?

Since you're doing this to learn, maybe a more R-like approach to in-place modification is a replacement function

`append_to<-` = function(x, ..., value)
    append(x, ..., values=value)

used as

x = 1:5
append_to(x) <- 5:1
y = 1:5
append_to(y, after=3) <- c(3:1, 1:3)

resulting in

> x
 [1] 1 2 3 4 5 5 4 3 2 1
> y
 [1] 1 2 3 3 2 1 1 2 3 4 5

This is very un-R but:

Append <- function(x, y) {
  assign(deparse(substitute(x)),append(x,y), envir = .GlobalEnv)
}

So you can do things like:

x <- 1:5

y <- 6

Append(x, y)

x # has a 6 at the end

edit: Another Carl pointed this out in the comments

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM