persephone
persephone

Reputation: 420

For loop: paste index into string

This may strike you as odd, but I want to exactly achieve the following: I want to get the index of a list pasted into a string containing a string reference to a subset of this list.

For illustration:


l1 <- list(a = 1, b = 2)
l2 <- list(a = 3, b = 4)
l <- list(l1,l2)

X_l <- vector("list", length = length(l))

for (i in 1:length(l)) {
  
 X_l[[i]] = "l[[  #insert index number as character# ]]$l_1*a"
  
}

In the end, I want something like this:


X_l_wanted <- list("l[[1]]$l_1*a","l[2]]$l_1*a")

Upvotes: 0

Views: 887

Answers (3)

Ronak Shah
Ronak Shah

Reputation: 388982

You can use sprintf/paste0 directly :

sprintf('l[[%d]]$l_1*a', seq_along(l))
#[1] "l[[1]]$l_1*a" "l[[2]]$l_1*a"

If you want final output as list :

as.list(sprintf('l[[%d]$l_1*a', seq_along(l)))

#[[1]]
#[1] "l[[1]]$l_1*a"

#[[2]]
#[1] "l[[2]]$l_1*a"

Using paste0 :

paste0('l[[', seq_along(l), ']]$l_1*a')

Upvotes: 2

DaveArmstrong
DaveArmstrong

Reputation: 21937

Or you could do it with lapply()

library(glue)
X_l <- lapply(1:length(l), function(i)glue("l[[{i}]]$l_l*a"))
X_l
# [[1]]
# l[[1]]$l_l*a

# [[2]]
# l[[2]]$l_l*a

Upvotes: 1

Duck
Duck

Reputation: 39595

Try paste0() inside your loop. That is the way to concatenate chains. Here the solution with slight changes to your code:

#Data
l1 <- list(a = 1, b = 2)
l2 <- list(a = 3, b = 4)
l <- list(l1,l2)
#List
X_l <- vector("list", length = length(l))
#Loop
for (i in 1:length(l)) {
  
  #Code
  X_l[[i]] = paste0('l[[',i,']]$l_1*a')
  
}

Output:

X_l

[[1]]
[1] "l[[1]]$l_1*a"

[[2]]
[1] "l[[2]]$l_1*a"

Upvotes: 1

Related Questions