user14874827
user14874827

Reputation: 23

Creating a vector from a loop outputs in R

I'm trying generate effcient code to create a vector that is used to replace names of variables in a dataframe to function in a larger script. More specifically, I want to change "A1" to "A.1" and "A2" to "A.2" and so on up to "'Letter'.8. I succeeded in a loop that does this, but cannot seem to output it to a vector. Below is the code and the output. I've tried various ways to vectorize the output based on similar questions, but nothing has worked...

#1 define letter vector and add function

     v1 = LETTERS[1:10]
     add = function(x, inc = 1) {
     y <- x + inc
     }

#create loop to generate desired names

     d <- add(0)
     while (d < 9) {
     for (l in v1) {
     print(paste(l,".",d))
     }
     d <- add(d)
     }

Upvotes: 2

Views: 86

Answers (3)

Amal K
Amal K

Reputation: 4929

You can use the append() function:

v1 = LETTERS[1:10]
add = function(x, inc = 1) {
     y <- x + inc
 }
vct = c()
d <- add(0)
while (d < 9) {
  for (l in v1) {
     vct <- append(vct, paste(l,".",d))
  }
  d <- add(d)
}
print(vct)

Upvotes: 1

Ian Campbell
Ian Campbell

Reputation: 24888

Is this what you're looking for?

paste0(rep(LETTERS[1:10],times=8),".",rep(1:8,each = 10))
[1] "A.1" "B.1" "C.1" "D.1" "E.1" "F.1" "G.1" "H.1" "I.1" "J.1" "A.2" "B.2" "C.2" "D.2" "E.2" "F.2" "G.2" "H.2" "I.2" "J.2" "A.3" "B.3"
[23] "C.3" "D.3" "E.3" "F.3" "G.3" "H.3" "I.3" "J.3" "A.4" "B.4" "C.4" "D.4" "E.4" "F.4" "G.4" "H.4" "I.4" "J.4" "A.5" "B.5" "C.5" "D.5"
[45] "E.5" "F.5" "G.5" "H.5" "I.5" "J.5" "A.6" "B.6" "C.6" "D.6" "E.6" "F.6" "G.6" "H.6" "I.6" "J.6" "A.7" "B.7" "C.7" "D.7" "E.7" "F.7"
[67] "G.7" "H.7" "I.7" "J.7" "A.8" "B.8" "C.8" "D.8" "E.8" "F.8" "G.8" "H.8" "I.8" "J.8"

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389325

You can use outer in base R :

result <- c(outer(LETTERS[1:10], 1:8, paste, sep = '.'))
result

# [1] "A.1" "B.1" "C.1" "D.1" "E.1" "F.1" "G.1" "H.1" "I.1" "J.1" "A.2" "B.2" "C.2" "D.2"
#[15] "E.2" "F.2" "G.2" "H.2" "I.2" "J.2" "A.3" "B.3" "C.3" "D.3" "E.3" "F.3" "G.3" "H.3"
#[29] "I.3" "J.3" "A.4" "B.4" "C.4" "D.4" "E.4" "F.4" "G.4" "H.4" "I.4" "J.4" "A.5" "B.5"
#[43] "C.5" "D.5" "E.5" "F.5" "G.5" "H.5" "I.5" "J.5" "A.6" "B.6" "C.6" "D.6" "E.6" "F.6"
#[57] "G.6" "H.6" "I.6" "J.6" "A.7" "B.7" "C.7" "D.7" "E.7" "F.7" "G.7" "H.7" "I.7" "J.7"
#[71] "A.8" "B.8" "C.8" "D.8" "E.8" "F.8" "G.8" "H.8" "I.8" "J.8"

Upvotes: 1

Related Questions