qnp1521
qnp1521

Reputation: 896

Pass concatenated string as function argument in R

I'm trying to create a concatenated string and pass it to a function. Suppose, I want to create a list of data frame that I can pass into a function. The problem is that the concatenated string using "noquote" function is treated as a "noquote" object, not as a list that I want. Here's a reproducible example. If I define data using data <- dflist1, then I get what I want, but when I try data1 <- noquote(paste0("dflist", selection)), it does not return the same list.

Is there a way I can create the list as I want by only changing selection?

In the real problem I face, there're multiple function arguments that I need to change in this way, so learning how to do this trick would be very helpful.

Any comments would be much appreciated!

a <- data.frame(aa = c(1,2,3), bb = c(4,5,6))
b <- data.frame(cc = c(11,12,13), dd = c(41,51,61))

dflist1 <- list(a, b)
dflist2 <- list(a, b, a, b)

selection <- "1"   # I want to make a choice here

data <- dflist1
data1 <- noquote(paste0("dflist", selection))

print(data1)
[1] dflist1

print(data)
[[1]]
  aa bb
1  1  4
2  2  5
3  3  6

[[2]]
  cc dd
1 11 41
2 12 51
3 13 61

class(data)
[1] "list"
class(data1)
[1] "noquote"

Upvotes: 2

Views: 250

Answers (1)

akrun
akrun

Reputation: 887951

We can use get to return the values

get(data1)
#[[1]]
#  aa bb
#1  1  4
#2  2  5
#3  3  6

#[[2]]
#  cc dd
#1 11 41
#2 12 51
#3 13 61

If we check the str(data1), will understand that on top of "character", it adds a class noquote

str(data1)
#'noquote' chr "dflist1"

class(data1)
#[1] "noquote"

by changing the attribute

noquote
#function (obj, right = FALSE) 
#{
#    if (!inherits(obj, "noquote")) 
#        class(obj) <- c(attr(obj, "class"), if (right) c(right = "noquote") else "noquote")
#    obj
#}

The paste0 returns the object name as string and there is no need to use noquote. Simply, wrap with get and it returns the value of that list or use mget if there are multiple objects

Upvotes: 4

Related Questions