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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With