How do I get a function to retain values I assign? (R) -
this follow-up question posted earlier how assign values vector of names: r: how concisely assign names vector parameter components?
i want assign values vector of names , need in multiple different functions of form function2 in code below. rather insert code every function, i'd write subroutine of form function1 below, , call in each function. unfortunately, name assignments kept within function1 when call , don't survive used within "return( adam +...)" part. suspect how specify environment assign function, don't know how fix (i don't want assign names globally). can help?
the rough code i'm trying use below:
function1 <- function(vector, names){ (i in 1:length(vector){ assign(names[i], vector[,i], envir = environment()) } } function2 <- function(vector){ names1 <- c("adam", "becky", "charlie",...) function1(vector,names1) return( adam + becky^2 - 2*charlie*david +...) }
you don't want write function name assignment, let alone 1 contains loop.
use named vector instead. example:
vec1 <- c("this","that","the other") vec2 <- c(5,7,9) names(vec2) <- vec1
then works
vec2['that'] <- vec2['that'] + 1 print(vec2) other 5 8 9
Comments
Post a Comment