climsaver
climsaver

Reputation: 617

Fill empty vectors in a loop

I created four empty vectors (series_p_river) which I would like to fill in a loop instead of one by one. The data that is supposed to be filled in the vectors contain mean values of four different river basins (Main, Danube, Isar and Inn), one value for each river and each timestep. For example Main.4_mean, Danube.18_mean, Isar.2_mean, Inn.8_mean. The number of time steps ntime is the length of the empty vectors.

The one by one way works well of course, but is not very elegant:

for (j in 1:ntime) {
  series_p_Main[j] <- get(paste0("Main.", j, "_mean"))
  series_p_Danube[j] <- get(paste0("Danube.", j, "_mean"))
  series_p_Isar[j] <- get(paste0("Isar.", j, "_mean"))
  series_p_Inn[j] <- get(paste0("Inn.", j, "_mean"))
}

Is there a way to achieve this in a loop or in another way?

Upvotes: 0

Views: 107

Answers (1)

r2evans
r2evans

Reputation: 160417

It appears that you'll be doing something similar with each river, so I generally recommend a list of vectors instead of individual objects in your environment. That suggests that instead of series_p_Main, you might then need to reference series_p[["Main"]]. The added benefit of using a list, though, is that when you do the same to each vector, you can use lapply instead of manually doing each one.

For instance,

ntime <- 3
series_p <- lapply(setNames(nm = c("Main", "Danube", "Isar", "Inn")),
                   function(nm) sprintf("%s.%s_mean", nm, seq_len(ntime)))
str(series_p)
# List of 4
#  $ Main  : chr [1:3] "Main.1_mean" "Main.2_mean" "Main.3_mean"
#  $ Danube: chr [1:3] "Danube.1_mean" "Danube.2_mean" "Danube.3_mean"
#  $ Isar  : chr [1:3] "Isar.1_mean" "Isar.2_mean" "Isar.3_mean"
#  $ Inn   : chr [1:3] "Inn.1_mean" "Inn.2_mean" "Inn.3_mean"
series_p[["Main"]]
# [1] "Main.1_mean" "Main.2_mean" "Main.3_mean"

Or if ntime is actually a vector, then remove seq_len:

ntime <- c(4, 8, 12)
series_p <- lapply(setNames(nm = c("Main", "Danube", "Isar", "Inn")), function(nm) sprintf("%s.%s_mean", nm, ntime))
series_p[["Main"]]
# [1] "Main.4_mean"  "Main.8_mean"  "Main.12_mean"

Upvotes: 1

Related Questions