scoping - update a data frame and environment in R -
i not quite sure why data frame object not update
d <- data.frame(titi=c(0)) (function(dataset) { dataset[["toto"]] <- 1; print(names(dataset)) #has "toto" , "titi" })(d) print(names(d)) # no has "toto", "titi"
what going on here ?
i have workaround in code capture variable , update captured <<-
, i'd know mechanism.
i aware of danger of mutation in general etc.. dont understand mechanism @ play here.
edit
although seems consensus language level feature, dont follow argument, if use close structure, data table, can mutate :
d <- data.table(titi=c(0)) (function(dataset) { dataset[,toto:=1] print(names(dataset)) #"titi" "toto" })(d) print(names(d)) #"titi" "toto"
what going on here?
you haven't read the introduction r, not section on assignment within functions or section on writing own functions
two pertinent quotes are
note ordinary assignments done within function local , temporary , lost after exit function.
and
the value of expression value returned function.
in case final value of function call names
return character vector....
scoping can complex issue, example simple case.
if want more complete reference @ r language definition.
but data.table
it....
yes, :=
in data.table
assigns reference. not ordinary assignment.
data.table
inherits data.frame
. not identical, , :=
assigning reference (also setattr
) assign reference. goes against standard r
idiom. can cause issues see why data.table update names(dt) reference, if assign variable?
there other ways around it, standard r
idiom ordinary assignment within functions local , temporary , lost after exit.
you consider using referenceclasses
(see ?setrefclass
)
it not limited lists / data.frames. atomic vectors same
mydf <- data.frame(a=1) mylist <- list(a=1) mynumeric <- c(a = 1) mydf <- data.frame(a=1) mylist <- list(a=1) mynumeric <- c(a = 1) foo <- function(x){x[['b']] <- 1; print(names(x))} # data.frame foo(mydf) # [1] "a" "b" mydf # # 1 1 # list foo(mylist) # [1] "a" "b" mylist # $a # [1] 1 # atomic foo(mynumeric) # [1] "a" "b" mynumeric # # 1
Comments
Post a Comment