Home > Net >  R: create a vector iteratively out of named vectors
R: create a vector iteratively out of named vectors

Time:09-21

I have the following (character) vectors, that I want to merge in bigger vectors with the year content

text_2020_0001
text_2020_0002
...
text_2020_0320

text_2021_0001
text_2021_0002
...
text_2021_0237

What I want to get is

text_2020 <- c(text_2020_0001,text_2020_0002,...,text_2020_0320)
text_2021 <- c(text_2021_0001,text_2021_0002,...,text_2021_0237)

I have coded this double loop, that doesn't work, because c(paste0(), ...) is not the way to go, but I can't figure out what I should use.

for (i c(20,21)) {
    assign(paste0("text_20",i),
           paste0("text_20",i,"_0001"))
  for(j in (1,400) {
    assign(paste0("text_20",i),
           c(paste0("text_20",i),paste0("text_20",i,"_",formatC(j 1,width = 3, format = "d", flag = "0"))))
  }
}

Thanks in advance for your help!

CodePudding user response:

Create the object names with sprintf

txt1 <- sprintf('text_%d_d', rep(c(2020, 2021), c(320, 237)), c(1:320, 1:237))

-output

> head(txt1)
[1] "text_2020_0001" "text_2020_0002" "text_2020_0003" "text_2020_0004" "text_2020_0005" "text_2020_0006"
> tail(txt1)
[1] "text_2021_0232" "text_2021_0233" "text_2021_0234" "text_2021_0235" "text_2021_0236" "text_2021_0237"

If it needs to be separate

txt2020 <- sprintf('text_2020_d', 1:320)
txt2021 <- sprintf('text_2021_d', 1:237)

If these are objects created in the global environment (not recommended), we can load those objects with mget

txt2020_out <- unlist(mget(txt2020), use.names = FALSE)
txt2021_out <- unlist(mget(txt2021), use.names = FALSE)

Also, these objects can be automatically loaded with a regex pattern in ls mget into a list

txt2020_out <- unlist(mget(ls(pattern = 'text_2020_\\d{4}')), use.names = FALSE)
txt2021_out <- unlist(mget(ls(pattern = 'text_2021_\\d{4}')), use.names = FALSE)
  •  Tags:  
  • r
  • Related