Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pasting together two vectors with expression command

Tags:

r

I'm trying to create a y-axis label that is generated by pasting together two vectors that are the same length. The catch is that the first element needs to be italicized. Here's an example...

n <- 1:5
t <- LETTERS[1:5]
together <- paste(t, n)

plot(x=1:5, y=1:5, yaxt="n")
axis(2, at=1:5, label=together, las=2)

So, I'd like the t elements italicized. I've looked around expression, bquote, and substitute and am not making much progress. Anyone got a hint to help me here?

like image 202
PD Schloss Avatar asked Dec 03 '25 15:12

PD Schloss


2 Answers

This is a bit tricky because the expression function expects a list of expressions. Therefore you need to convert the strings returned by paste to a list of unevaluated expressions. One way is like this

together <- do.call(expression, as.list(parse(text = paste0("italic(", t, ")~", n))))
like image 110
tmpname12345 Avatar answered Dec 05 '25 07:12

tmpname12345


You could use bquote

together <- as.expression(sapply(seq_along(t), function(i) 
                   bquote(italic(.(t[i]))*.(n[i]))))

Or using for loop

 v1 <- c()
 for(i in seq_along(t)){
   v1 <- c(v1, bquote(italic(.(t[i]))*.(n[i])))
  }
 together <- as.expression(v1) 
like image 32
akrun Avatar answered Dec 05 '25 08:12

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!