Home > OS >  How to add superscript to text in data frame?
How to add superscript to text in data frame?

Time:08-25

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)

CodePudding user response:

Much better to use kableExtra, view() isn't really provided for tables. There is quite a enter image description here

CodePudding user response:

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 p-value
1 Variable 1 (mg L⁻¹)         NA         NA      NA
2 Variable 2 (g kg⁻¹)         NA         NA      NA
3    Variable 3 (ppt)         NA         NA      NA
  •  Tags:  
  • r
  • Related