首页 > 解决方案 > 更改数据框的列名仅用于显示目的

问题描述

有没有办法仅出于显示目的更改数据框的列标题的名称。例如

虹膜数据具有以下默认列

ini_col <- c("Sepal.Length","Sepal.Width","Petal.Length","Petal.Width" ,"Species")

如果我需要将其更改为新列下方。但只是显示目的。意思是,旧列的引用不应该消失。例如我应该仍然能够执行iris[["Species"]]而不是iris[["Category"]]

new_col <- c("Sep Len","Sep Wid","Pet Len","Pet Wid","Category")
head(iris)
         Sep Len     Sep Wid     Pet Len     Pet Wid Category 
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

我们实际上可以使用下面的代码 Code 1 below

mtcars2 <- 
  set_label(mtcars,
            am = "Automatic",
            mpg = "Miles per gallon",
            cyl = "Cylinders",
            qsec = "Quarter mile time")

但是我有一个数据框,其中有旧列和新列。我们可以在上面的代码 1 中使用这个数据框吗

df
Old COl    new COl
am         Automatic
mpg    Miles per gallon
cyl       Cylinders
qsec   Quarter mile time

我们可以在执行 Code1 时使用这个数据框吗?

标签: r

解决方案


正如在类似问题中链接的那样,kableknitr包中可以轻松更改名称以进行显示,而无需更改数据框:

knitr::kable(head(iris), 
             col.names = c("Speal length", "Speal Width",
"Petal Length", "Petal Width", "Species"))

在此处输入图像描述


推荐阅读