LIPD
LIPD

Reputation: 15

How do I get a function to retain values I assign? (R)

This is a follow-up to this question I posted earlier about how to assign values to a vector of names: R: How do I concisely assign names to vector parameter components?

I want to assign values to a vector of names and I need to do this in multiple different functions of the form function2 in the code below. Rather than insert the code into every function, I'd like to write a subroutine of the form function1 below, and call that in each function. Unfortunately, the name assignments are kept within function1 when I call it and don't survive to be used within the "return( adam +...)" part. I suspect this is something to do with how I specify the environment for the assign function, but I don't know how to fix it (I don't want to assign the names globally). Can anyone help?

The rough code I'm trying to use is below:

function1 <- function(vector, names){

for (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 +...)

 }

Upvotes: 0

Views: 857

Answers (2)

akrun
akrun

Reputation: 886938

You may try:

function1 <- function(vector, names, envir){
for (i in 1:length(vector)){
 assign(names[i], vector[i], envir = envir)
 }
 }

function2 <- function(vector){
names1 <- c("adam", "becky", "charlie", "david")
function1(vector,names1, envir=environment())
return(adam + becky^2 - 2*charlie*david)
}


v1 <- 1:4
function2(v1)
#[1] -19
adam
#Error: object 'adam' not found

Upvotes: 0

hedgedandlevered
hedgedandlevered

Reputation: 2384

you don't want to write a function for name assignment, let alone one that contains a loop.

Use a named vector instead. For example:

vec1 <- c("this","that","the other")
vec2 <- c(5,7,9)
names(vec2) <- vec1

then this works

vec2['that'] <- vec2['that'] + 1
print(vec2)
 this      that the other 
    5         8         9 

Upvotes: 1

Related Questions