tassones
tassones

Reputation: 1692

How to add superscript to text in data frame?

I am trying to get in the habit of making tables in R rather than "by hand" in MS Excel. How can I make my text superscripted within a data frame?

Example Data:

df <- data.frame(matrix(ncol = 4, nrow = 3))
colnames(df)[1:4] <- c("Variable","Location 1","Location 2","p-value")
df$Variable <- c("Variable 1 (mg L<sup> -1</sup>)",
                 "Variable 2 (g kg<sup> -1</sup>)",
                 "Variable 3 (ppt)")
View(df)

I have also tried the following notation but it also did not work.

df <- data.frame(matrix(ncol = 4, nrow = 3))
colnames(df)[1:4] <- c("Variable","Location 1","Location 2","p-value")
df$Variable <- c(expression(paste("Variable 1 (mg   ",  L^-1,")")),
                 expression(paste("Variable 2 (g   ",  kg^-1,")")),
                 "Variable 3 (ppt)")
View(df)

Upvotes: 0

Views: 1434

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 270248

You can use unicode characters to the extent that they are supported. This worked for me in the Rgui R console on Windows using R 4.2.1 .

df <- data.frame(Variable = c("Variable 1 (mg L\u207b\u00b9)",
                              "Variable 2 (g kg\u207b\u00b9)",
                              "Variable 3 (ppt)"))
df$"Location 1" <- df$"Location 2" <- df$pvalue <- NA

df

giving:

             Variable Location 1 Location 2  pvalue
1 Variable 1 (mg L⁻¹)         NA         NA      NA
2 Variable 2 (g kg⁻¹)         NA         NA      NA
3    Variable 3 (ppt)         NA         NA      NA

Upvotes: 1

user438383
user438383

Reputation: 6227

Much better to use kableExtra, view() isn't really provided for tables. There is quite a comprehensive documentation on it here, it is quite useful.

library(kableExtra)
kbl(df, escape=F)

enter image description here

Upvotes: 1

Related Questions