Home > Software design >  How to get part of column in df in italics?
How to get part of column in df in italics?

Time:06-13

I have a dataframe as follows:

number <- c(34,36,67,87,99)
mz <- c("m/z 565.45","m/z 577.45","m/z 65.49","m/z 394.22","m/z 732.43")  
df <- data.frame(number, mz)

However, I want the m/z part in italics, but I cannot figure out how to.

df$mz <- gsub('m/z', italic('m/z'), df$mz)

This does not work, I get the error:

Error in italic("m/z") : could not find function "italic"

This also does not work:

df$mz <- gsub('m/z', expression(italic('m/z')), df$mz)

I don't get an error but I get literally 'italic('m/z')' in my dataframe. Is there any way around this?

EDIT: The reason I want to do this is because I'm going to use the df to make a plot and I need the m/z to be in italics in the plot

CodePudding user response:

You should store mz as character strings, then parse at the time of plotting:

df$mz <- sub('m/z', 'italic(m/z)~', df$mz)

A base R plot would then look like this:

plot(1:5, df$number, xaxt = 'n', xlab = 'mz')
axis(1, at = 1:5, labels = parse(text = df$mz))

enter image description here

And a ggplot like this:

ggplot(df, aes(factor(1:5), number))  
  geom_point()  
  scale_x_discrete(labels = parse(text = df$mz), name = 'mz')

enter image description here

  •  Tags:  
  • r
  • Related