I am trying to create a list of requests called requests. I have a list of hundreds of products, but I simplify for this example code.
products <- list()
products[[1]] <- c("77295T", "67619Q", "9528QR")
products[[2]] <- c("B7295T", "676193")
requests <- vector("list",length(products[[1]]))
length(requests)
i <- 1
for (i in 1:(length(products[[1]]))) {
requests[[i]] <- cat('"',noquote(products[[1]][[i]]),'~XPORT"', sep = '')
}
results in:
"77295T~XPORT""67619Q~XPORT""9528QR~XPORT"
The end result I am looking for is a request list of length 3 with the following three elements:
requests[[1]]
"77295T~XPORT"
requests[[2]]
"67619Q~XPORT"
requests[[3]]
"9528QR~XPORT"
Background: Eventually I want requests to be a nested list (a list of lists); in my dataset products is a list, so that is why I provide products[[2]], even though my question relates to just iterating over products[[1]]. Replacingproducts[[1]]` with an equivalent products1 also creates the same output. That code is here:
products1 <- c("77295T", "67619Q", "9528QR")
i <- 1
for (i in 1:(length(products1))) {
requests[[i]] <- cat('"',noquote(products1[[i]]),'~XPORT"', sep = '')
}
This more simple code provides the same results:
"77295T~XPORT""67619Q~XPORT""9528QR~XPORT"
I do realize that the for loop I called may not be necessary. I am trying to gradually learn how to "vectorize" my R code. Any suggestion for further vector-elegance in this code would be appreciated.
requests <- as.list(paste(products[[1]], "XPORT", sep="~"))is the simplest answer.lapply(products[[1]], function(x){ paste0(x, "~XPORT")})should also workpastedoes the work under the hood.