0

I have variable a as string:

a = "jul_0_baseline,jul_1_baseline,...jul_11_baseline,jul_12_baseline"

When I try to merge the following zoo series to one table using:

temp <- merge(jul_0_baseline,jul_1_baseline,...jul_11_baseline,jul_12_baseline)

it works, however when I try to merge it using

temp <- merge(a)

I get an error as it the variable a is a string (even though the text is correct). I am assuming that it is effectively inputting

temp <- merge("jul_0_baseline,jul_1_baseline,...jul_11_baseline,jul_12_baseline")

Any help would be greatly appreciated

a is a string because it is created using the code:

a <- paste("jul","0","baseline",sep = "_")
    for (d in 1:12){ b <- paste("jul",d,"baseline",sep = "_")
                     a <- paste(a,b, sep=",")
                   }
989
  • 12,579
  • 5
  • 31
  • 53

2 Answers2

0

Since each jul_i_baseline listed in the string a corresponds to an actual object, you can do this:

temp <- Reduce(function(...) merge(..., all=T), mget(strsplit(a, ",")[[1]]))

The strsplit() function splits a into a vector of strings where each element is "jul_i_baseline". It returns a one-element list, so we can use [[1]] to get the vector of strings.

mget() interprets the list of variables in strings as objects. It returns a list where each element corresponds to the object. So each element is the actual Zoo object jul_i_baseline.

Reduce(function(...) merge(..., all=T), <list>) merges the objects stored in each element of the list. Assuming the objects have a common variable on which you want to merge, you can also add a by variable in merge().


An alternate approach as suggested in the comments is to use do.call() which would work since you're dealing with Zoo objects. (The former approach works with non-Zoo objects as well but this does not.) The command would be structured like so:

temp <- do.call(merge, mget(strsplit(c, ",")[[1]]))

Again we're getting the objects using mget() and strsplit().


@G.Grothendiek's suggestion of using eval(parse(...)) also works in this situation. However, many R users discourage the use of eval(parse(...)) in general. See here.

Community
  • 1
  • 1
Alex A.
  • 5,466
  • 4
  • 26
  • 56
0

Form the entire command string (including merge) and then parse and evaluate it:

eval(parse(text = sprintf("merge(%s)", a)))
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341