manish p
manish p

Reputation: 187

Change the column names of the data frame only for display purpose

Is there a way to change the names of the column headers of a data frame only for display purpose. For example

iris data has below default columns

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

In case if I need to change it to below new columns. But only display purpose. Meaning, the reference of the old columns should not go away. For example I should still be able to execute iris[["Species"]] and not 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

We can actually make use of below code Code 1 below

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

But I have a dataframe where in there are old columns and new columns. Can we make this dataframe use in Code 1 above

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

Can we use this dataframe in executing Code1?

Upvotes: 0

Views: 211

Answers (1)

Mikey Harper
Mikey Harper

Reputation: 15369

As linked in a similar question, kable from the knitr package makes it easy to change the names for display without altering the data frame:

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

enter image description here

Upvotes: 1

Related Questions