r - update function inputs in global environment -
let's have dataframe df , list obj.
df<- data.frame(x=c(1, 2, 3, 4), y=c(1, 2, 3, 4)) obj <- list(data.frame(z=c(0, 0, 0, 0), a=c(0, 0, 0, 0)), data.frame(b=c(0, 0, 0, 0))) i create function myfun modifies 1 column in df , adds list obj. how update both x , o in global environment? in other words, how have function update df , obj?
myfun <- function(x, o) { x[1] <- x[,1]*2 o <- list(o, x[1]) } myfun(df, obj)
there's global assignment (eg <<-),
myfun1 <- function(x, o) { x[1] <- x[,1]*2 o <- list(o, x[1]) df <<- x obj <<- o } or try returning objects function, using list2env multiassignment.
myfun2 <- function(x, o) { x[1] <- x[,1]*2 o <- append(o, x[1]) list(obj=o, df=x) #setting names here important list2env } list2env(myfun2(df, obj), environment()) alternatively, pass in environment. in r, environments pass-by-reference,
myfun3 <- function(e) { e$df[1] <- e$df[,1]*2 e$obj <- append(e$obj, e$df[1]) } myfun3(environment())
Comments
Post a Comment