R. Joe - 2 months ago 7

R Question

I wish to print meters squared in R but I’m not having success.

This is an example of the code I am working on:

`bmi <- c(24,28,31)`

print(paste0("Your body mass index is ", bmi, "kg/m^2"))

# [1] "Your body mass index is 24kg/m^2"

# [2] "Your body mass index is 28kg/m^2"

# [3] "Your body mass index is 31kg/m^2"

Suggestions?

Answer

You can just use the UTF-8 Character "SUPERSCRIPT TWO", ² (see here). If you properly encoded your R script (or directly enter into the terminal), it'll work just fine.

If you don't have this option (or you can't type this letter), use the `\u`

escape sequence: `\u00B2`

```
bmi <- c(24,28,31)
cat(paste0("Your body mass index is ", bmi, "kg/m²"), sep = "\n")
cat(paste0("Your body mass index is ", bmi, "kg/m\u00B2"), sep = "\n")
# Your body mass index is 24kg/m²
# Your body mass index is 28kg/m²
# Your body mass index is 31kg/m²
```

Newer R versions allow you to specify the file encoding with `source`

, so that would be

`source("myFancyScript.R", encoding = "UTF-8")`

Source (Stackoverflow)

Comments