Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I concatenate compound language objects in R?

Tags:

r

I am trying to build up expressions in R by concatenating smaller expressions. For example in S+ I can do this:

> x = substitute({a;b;c})
> y = substitute({d;e;f})
> c(x,y)
{
    a
    b
    c
    d
    e
    f
}

but if I try it in R, I get this:

> c(x,y)
[[1]]
{
    a
    b
    c
}

[[2]]
{
    d
    e
    f
}

Should I be doing this another way?

like image 207
Mike Dunlavey Avatar asked Mar 16 '12 21:03

Mike Dunlavey


1 Answers

The comments attached to @baptiste's answer make the point that x and y are not objects of type "expression" (one of the nine basic vector types used by R). Thus, they can't by combined by using c(), as they could if they were in fact expression vectors.

If you really do want to combine objects of class "{" (which are called "compound language objects" in this section of the R Language Definition) you could do something like this:

x <- substitute({a;b;c})
y <- substitute({d;e;f})
class(x)
# [1] "{"

as.call(c(as.symbol("{"), c(as.list(x)[-1], as.list(y)[-1])))
{
    a
    b
    c
    d
    e
    f
}

Then, if you were going to be doing this frequently, you could create a function that combines an arbitrary set of objects of class "{":

myC <- function(...) {
    ll <- list(...)
    ll <- lapply(ll, function(X) as.list(X)[-1])
    ll <- do.call("c", ll)
    as.call(c(as.symbol("{"), ll))
}

# Try it out
myC(x, y, y, y, x)
like image 129
Josh O'Brien Avatar answered Sep 21 '22 14:09

Josh O'Brien