如何在 R 中将单位添加到 table

How to add units to a table in R

我有以下代码在 R 中创建 table。如何将单位添加到 HeightWeight 以及 BMI? (所以就像 Height (in)Weight (lb)BMI (kg/m2)

Height <- c(66, 73, 65, 68, 71)
Weight <- c(121,191,177,159,152) 
#pound to kilogram and inche to meter
#BMI=kg/m^2
BMI = Weight * 0.45/(Height * 0.02)^2  
expn <- data.frame (Height, Weight, BMI)
knitr::kable (expn, caption = "Body Measurments", align = c ("c", "c"))

如果您的意思是向 table 中的元素添加单位,

expn <- data.frame (Height, Weight, BMI) %>%
  mutate(Height = paste(Height, "in"),
           Weight = paste(Weight, "lb"),
           BMI = paste(BMI, "kg/m2"))
knitr::kable (expn, caption = "Body Measurments", align = c ("c", "c"))

Table: Body Measurments

| Height | Weight |          BMI           |
|:------:|:------:|:----------------------:|
| 66 in  | 121 lb |      31.25 kg/m2       |
| 73 in  | 191 lb | 40.3218239819854 kg/m2 |
| 65 in  | 177 lb | 47.1301775147929 kg/m2 |
| 68 in  | 159 lb | 38.6840397923875 kg/m2 |
| 71 in  | 152 lb | 33.9218409045824 kg/m2 |

tibble,

units <- c("in", "lb", "kg/m2")
expn <- data.frame (Height, Weight, BMI)%>% map2_dfc(units, ~set_units(.x, .y, mode = "standard")) 
expn

  Height Weight      BMI
    [in]   [lb]  [kg/m2]
1     66    121 31.25000
2     73    191 40.32182
3     65    177 47.13018
4     68    159 38.68404
5     71    152 33.92184

使用kableExtra,

expn <- data.frame (Height, Weight, BMI)
colNames <- names(expn)
units <- c("$lb$", "$in$", "$kg/m2$")
knitr::kable (expn, caption = "Body Measurments", align = c ("c", "c"), col.names = units, escape = F) %>%
  kableExtra::add_header_above(header = colNames, line = F, align = "c")

如果您只想将单位添加到列名中,您可以使用 colnamespaste0

Height <- c(66, 73, 65, 68, 71)
Weight <- c(121,191,177,159,152) 
#pound to kilogram and inche to meter
#BMI=kg/m^2
BMI = Weight * 0.45/(Height * 0.02)^2  
expn <- data.frame (Height, Weight, BMI)
colnames(expn)<-paste0(colnames(expn), c(" (in)", " (lb)", " (kg/m2)"))
knitr::kable (expn, caption = "Body Measurements", align = c ("c", "c"))

Table:Body 测量值

Height (in) Weight (lb) BMI (kg/m2)
66 121 31.25000
73 191 40.32182
65 177 47.13018
68 159 38.68404
71 152 33.92184