landroni
landroni

Reputation: 2988

How to insert a backslash (\) into a data frame column name?

For display purposes, I am trying to insert one backslash (\) into a data frame column name.

If I simply insert the backslash ('\'), then for some reason it disappears from the column name:

x <- head(mtcars[ , 1:3])

names(x)[1] <- "back \ slash"
##backslash missing
names(x)[1]
# [1] "back  slash"
x
#                   back  slash cyl disp
# Mazda RX4                21.0   6  160
# Mazda RX4 Wag            21.0   6  160
# Datsun 710               22.8   4  108
# Hornet 4 Drive           21.4   6  258
# Hornet Sportabout        18.7   8  360
# Valiant                  18.1   6  225

If however I try to escape the backslash ('\\'), then I get two backslashes in the column name:

names(x)[1] <- "back \\ slash"
##two backslashes
names(x)[1]
# [1] "back \\ slash"
x
#                   back \\ slash cyl disp
# Mazda RX4                  21.0   6  160
# Mazda RX4 Wag              21.0   6  160
# Datsun 710                 22.8   4  108
# Hornet 4 Drive             21.4   6  258
# Hornet Sportabout          18.7   8  360
# Valiant                    18.1   6  225

How can I insert one backslash (\) into a data frame column name?

Upvotes: 1

Views: 984

Answers (2)

r2evans
r2evans

Reputation: 160447

Since you're intending to use this with knitr::kable, then try this:

x <- mtcars[1:3,1:3]
x <- mtcars[1:4,1:3]
knitr::kable(x, col.names=replace(names(x), 1, "foo \\ bar"))
# |               | foo \ bar| cyl| disp|
# |:--------------|---------:|---:|----:|
# |Mazda RX4      |      21.0|   6|  160|
# |Mazda RX4 Wag  |      21.0|   6|  160|
# |Datsun 710     |      22.8|   4|  108|
# |Hornet 4 Drive |      21.4|   6|  258|

Upvotes: 2

Abdessabour Mtk
Abdessabour Mtk

Reputation: 3888

The default behaviour for R is to print the escape characters this happens even inside character vectors :

c("sd\\sd")
#> [1] "sd\\sd"
nchar("sd\\sd") 
#> [1] 5
# "sd\\sd" is 6 character if you count the second backslash
# while cat prints the actual string
cat(c("sd\\sd"))
#> sd\sd

Upvotes: 0

Related Questions