1

I have a base query that i am trying to add 14 other strings to, which are named query1:14

I am trying to combine them using paste and the following works for one query. However, i am trying to set this up in a function which will have the number of queries passed to it, to know how many it should loop/add into the final restuls

Here is some code to add one query, which works:

result<- paste(base_query, eval(as.name(paste0("query", 2)))

Here is something i tried to loop the queries added, to no success

range <- 14
result<- paste(base_query, while(loop<range){loop<-loop+1
                        eval(as.name(paste0("query", loop)))} 

I'm not sure how to get the names generated in the while loop to be added to the paste, thanks

Leo Cooper
  • 37
  • 5
  • 1
    Perhaps you meant `get(paste0("query", 2))` – akrun Aug 25 '22 at 16:11
  • It's easier to help you if you provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Aug 25 '22 at 17:50

1 Answers1

1

In general, it is preferable to store the queries 1-14 in a list, rather than store them separately in the global environment. That is why half of this solution entails getting the objects into a list, which is easily pasted together with the collapse argument of paste.

Also pay attention to stools::mixedsort, which sorts them in the order that I assume you want (incrementally 1 to 14).

# Generate the query objects
base_query = "The letters of the alphabet are:"
for (i in 1:14) {
  assign(x = paste0("query",i), value = LETTERS[i])
}

# Find all the query names, and sort them in a meaningful order
query_names = gtools::mixedsort(ls(pattern = "query*"))
query_names
#>  [1] "base_query" "query1"     "query2"     "query3"     "query4"    
#>  [6] "query5"     "query6"     "query7"     "query8"     "query9"    
#> [11] "query10"    "query11"    "query12"    "query13"    "query14"

# Now get the appropriate objects
query_list = lapply(query_names, function(x){
  get(x)
})

# Paste and collapse the contents of the list
paste(query_list, collapse = "")
#> [1] "The letters of the alphabet are:ABCDEFGHIJKLMN"

Created on 2022-08-26 by the reprex package (v2.0.0)

mhovd
  • 3,724
  • 2
  • 21
  • 47