Inserting double quotes inside a paste command to separate elements

Hello,
Let's say I have the following two objects.
vars = "x,y,z"
total= "Total"

I want to create the following one:

"ID" "x" "y" "z"

To do so, I’m trying to separate the elements from “var” as follows:

mylist = as.list(strsplit(vars, ",")[[1]])

Then, I’m using the “paste” function

paste("ID",mylist[[1]],mylist[[2]], mylist[[3]],sep=",") #Here I tried with sep= \”

However, I have no been being able to get what I want. I tried many combinations, but I was not able to get each element within double quotes. Can you please advise?

Further information: In case you are wondering why I want this, I’ll explain. I want to create a function that perform certain analyses. The first step is to read the data set I want along, along with specific variables:

MyFunc = function(id,vars,total){

mylist = as.list(strsplit(vars, ",")[[1]])

dat = subset(mydat, select = paste("id",mylist[[1]],mylist[[2]], mylist[[3]],sep=","))

}

MyFunc(id = "ID",
vars = "x,y,z",
total = "Total")

Thanks a lot for your support.
A.G.

Note: I do not provide an example data set because I don’t think is necessary.

Does the following function do what you want?

MyFunc = function(id,...,total){
  mylist <- unlist(list(...))
  mydat[, c(id, mylist)]
}
mydat <- data.frame(V1 = 1:3, x = 2:4, y = 3:5, z = 4:6, 
                    ID = c("A", "B", "C"))
MyFunc(id="ID","x","y","z",total="Total")
#>   ID x y z
#> 1  A 2 3 4
#> 2  B 3 4 5
#> 3  C 4 5 6

Created on 2022-01-11 by the reprex package (v2.0.1)
EDIT:
A better version of the function. I thought directly using c(...) would not work but it does.

MyFunc = function(id,...,total){
  mydat[, c(id, ...)]
}
1 Like

Hi FJCC,
Your suggestion works fine, but I need to pass the multiple variables to the function (i.e. x,y,z ) instead of only one "list" containing of the variables of interest (i.e. vars). Although I think I can live with that.
Thanks a lot.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.