简体   繁体   中英

Getting the value of a Variable which has its name based upon another variable (in R)

I have a list of variables E = (E1=300,E2=300,E3=300...E96=300), i am passing these to a function and need to use these variables in some equations inside a for loop. For eg :

for(i in 1:96)
{
  assign(paste("dE",i,sep=""),constant*corresponding E value) ### e.g dE1 = constant*E1
}

Is there an easy way to get the value of the Ei variables inside the for loop ?

Note : constant corresponds to any arbitrary constant value, its of no interest in the present context

If you have a named list E where each element is length-one, and a constant constant that is also length one, then you can do the operation without a loop.

E <- list(E1 = 300, E2 = 300, E3 = 300, E96 = 300)
constant <- 5

Since E has names, and they are already half of what we want for the names of the new values, then we can do something like

setNames(constant * do.call(c, E), paste0("d", names(E)))
#  dE1  dE2  dE3 dE96 
# 1500 1500 1500 1500 

Note that if E is an atomic vector (you didn't specify), then the operation is just

constant * E

If you need a list result you can wrap the constant * do.call(c, E) with as.list . And if you really want to send all those single values to the global environment as variables, then you can use

x <- setNames(constant * do.call(c, E), paste0("d", names(E)))
list2env(as.list(x), globalenv())

but I don't recommend it. It would be best to keep the values together in a named vector.

Pretty simple:

ei = E[paste("E", i, sep = "")]

Note, that this will fail if the corresponding Ei value doesn't exist.

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