how to use an atomic vector as a string for a graph title in R

800 views Asked by At

I'm trying to plot a graph from a matrix of z-scores in R, i would like to build a function to iterate through each column using the column header as part of the title and saving each graph as a png.I think I know how to do the iteration and saving graphs as pngs but I am getting stuck with using the vector as a string. I tried to upload the matrix with no column headers and then store matrix[1,] as a variable 'headers' to use. Then I tried to plot:

 plot(1:30, rnorm(30), ylim=c(-10,10), yaxs="i", xlab = "Region", ylab = "Z-Score",main = "CNV plot of " + headers[i], type = "n")

I get:

 Warning message:
 In Ops.factor(left, right) : + not meaningful for factors

I try without the '+' and it says:

 Error: unexpected symbol in ...

So then I looked around and found 'paste(headers[i],collapse=" ") which I though I could substitute in but it just puts the number '28' as the title.

I've tried what I thought was another potential solution:

 plot(1:30, rnorm(30), ylim=c(-10,10), yaxs="i", xlab = "Region", ylab = "Z-Score",main = "Z-scores of " $headers[i], type = "n")

and I get:

 Error in "Z-scores of "$headers : 
 $ operator is invalid for atomic vectors

I'm new to R and this seems like something that would be so simple if I happened to stumble across the right guide/tutorial after hours of google searching but I really don't have that kind of time on my hands. Any suggestions, pointers or solutions would be great??

2

There are 2 answers

0
Sven Hohenstein On BEST ANSWER

If you want to insert values from variables into strings for a plot title, bquote is the way to go:

headers <- c(28, 14, 7) # an examle
i <- 1

plot(1:30, rnorm(30), ylim=c(-10,10), yaxs="i",
     xlab = "Region", ylab = "Z-Score", type = "n",
     main = bquote("CNV plot of" ~ .(headers[i])) )

enter image description here

Have a look at the help page of ?bquote for further information.

2
BrodieG On

paste("CNV plot of", headers[i]), should work. You only need collapse if you are pasting vectors of length greater than one (headers[i] should be one length, even if header is not). R doesn't have any concatenation operators, unlike PHP, JS, etc (so +, &, . will not work, you have to use paste).

Note that your paste was paste(headers[i],collapse=" "), and if that just plotted 28, it suggests your headers vector doesn't contain what you think it does (if you didn't want 28 to be displayed, that is.

Try just looping through your vector and printing the paste command to screen to see what it displays (and also, just print the vector).