Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: What's the simplest way (one-liner?) to create a vector of expressions?

Tags:

r

Is there any way to create a vector of expressions in one line? I only know a two-liner with an ugly for-loop:

vexpr <- vector("expression", 7)
for(j in 1:7) vexpr[j] <- substitute(expression(italic(X[j.])), list(j.=j))[2]
like image 366
Marius Hofert Avatar asked Nov 26 '11 18:11

Marius Hofert


People also ask

How do you create a vector in R?

You can create a Vector in R using c() primitive function. In R programming, the Vector contains elements of the same type and the types can be logical, integer, double, character, complex or raw. Besides c() you can also create a vector using vector(), character() functions.

How do I make a vector of words in R?

c() function is used to create a vector. By passing all elements with characters to c() function it creates a character vector in R. Use typeof() to check whether the created is a character vector or not.

Which function should be used to create a vector in R?

2) Using the seq() function In R, we can create a vector with the help of the seq() function. A sequence function creates a sequence of elements as a vector.

What is an expression vector in R?

Those are calls (see call ) in R, and an R expression vector is a list of calls, symbols etc, for example as returned by parse . As an object of mode "expression" is a list, it can be subsetted by [ , [[ or $ , the latter two extracting individual calls etc.


1 Answers

as.expression( sapply(1:7, function(x) bquote(italic(X[.(x)]))) )
#-----------
# expression(italic(X[1L]), italic(X[2L]), italic(X[3L]), italic(X[4L]), 
#    italic(X[5L]), italic(X[6L]), italic(X[7L]))

identical(vexpr, as.expression( sapply(1:7, function(x) bquote(italic(X[.(x)]))) ) )
#[1] TRUE

Also:

parse(text= paste("italic(X[", 1:7, "])", sep="") )  # fewer keystrokes
#--------
# expression(italic(X[1]), italic(X[2]), italic(X[3]), italic(X[4]), 
#    italic(X[5]), italic(X[6]), italic(X[7]))

(The second one will not pass the identical() test because it carries the heritage of its construction with it. I think these are byte-code side-effects, an enhancement that appears in R version 2.14.0, so it may appear differently in earlier versions. You can check this by applying str() to it. It does, however, pass the test of applying proper x-axis labels to plot(1:7, xaxt="n"); axis(1,at=1:7, labels=...) )

like image 120
IRTFM Avatar answered Sep 27 '22 23:09

IRTFM