stringrgraphatomic-values

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


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??


Solution

  • 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.