2

I have many arrays to fill in R, each of which has a different name in a specific pattern. The problem I'm having is that I can't figure out how to refer to the array names as variables, so I can refer to them in a systematic way inside a loop. They are created using this loop, for example.

for (i in c(40,45,50,55,57,60,65)){
  assign(paste0('hdd_',as.character(i),'_365_z'), rep(NA,365))}

I want to fill each of these arrays, which are now named like this: hdd_40_365_z, hdd_45_365_z, etc.

Let's say I want to fill each of these arrays using a simple function like this:

my_func <- function(value,doy){
  return(value * doy/2)}  # doy = doy or 1:365

I can write a loop to do this:

for (j in c(40,45,50,55,57,60,65)){
    for (k in 1:365){
        # try to fill arrays one day at a time
        paste0('hdd_',as.character(j),'_365_z')[k] <- my_func(j,k)}}

Obviously, this doesn't work. I've tried using the following to do this, but it's not working. There has to be a way to be able to do something like this, I would think, but I can't figure out the combination of eval, parse, as.name, or something else to do it. Any help would be great. Thank you.

eval(parse(text = paste0('hdd_',as.character(j),'_365_z')[k] <- my_func(j,k)))
1
  • 1
    Do they have to be separate variables? Often it is much easier to use a single list() and have each variable become a list element. Commented Dec 22, 2021 at 16:26

1 Answer 1

1

You were close, especially since you already know assign. Besides assign, the trick is to get the vector and concatenate the result of my_func to the existing vector.

We initialize the objects using NULL instead of NA,

for (i in c(40, 45, 50, 55, 57, 60, 65)) {
  assign(paste0('hdd_', as.character(i), '_365_z'), NULL)
}

and c each result.

for (j in c(40, 45, 50, 55, 57, 60, 65)) {
  for (k in 1:365) {
    # try to fill arrays one day at a time
    x <- paste0('hdd_', as.character(j), '_365_z')
    assign(x, c(get(x), my_func(j, k)))
  }
}

Gives:

lapply(mget(ls(pattern='hdd')), head)
# $hdd_40_365_z
# [1]  20  40  60  80 100 120
# 
# $hdd_45_365_z
# [1]  22.5  45.0  67.5  90.0 112.5 135.0
# 
# $hdd_50_365_z
# [1]  25  50  75 100 125 150
# 
# $hdd_55_365_z
# [1]  27.5  55.0  82.5 110.0 137.5 165.0
# 
# $hdd_57_365_z
# [1]  28.5  57.0  85.5 114.0 142.5 171.0
# 
# $hdd_60_365_z
# [1]  30  60  90 120 150 180
# 
# $hdd_65_365_z
# [1]  32.5  65.0  97.5 130.0 162.5 195.0
Sign up to request clarification or add additional context in comments.

1 Comment

Wonderful, thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.