0

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")

3 Answers 3

2

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')
Sign up to request clarification or add additional context in comments.

Comments

1

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"

Comments

1

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

Comments

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.