'How to convert quotes of character elements to be surrounded by backticks instead of quotes in R
I have some characters stored as cols. The resulting output is as below:
cols = c("big creek", "gage creek", "garvey creek", "larches creek", "little usable")
cols
[1] "big creek" "gage creek" "garvey creek" "larches creek" "little usable"
However, I want the quotes to be replaced with backticks and the resulting output should be like this:
[1] `big creek` `gage creek` `garvey creek` `larches creek` `little usable`
Is there any way to get the same output for cols object in R?
Your help will be highly appreciated.
Regards, Farhan
Solution 1:[1]
Your strings don't actually have quotes, they just appear that way on the console. Probably it bothers you that you have to set backticks around variable names with spaces, when subsetting with $.
In R, syntactically valid object names should consist of letters, numbers, dots, and underscores only, no numbers or dots as the first character. You could easily fix that using make.names.
Example:
df <- data.frame(`big creek`=1:3, `gage creek`=4:6, `garvey creek`=7:9, check.names=F)
df
# big creek gage creek garvey creek
# 1 1 4 7
# 2 2 5 8
# 3 3 6 9
names(df)
# [1] "big creek" "gage creek" "garvey creek" ## invalid names
df$`big creek` ## rather annoying backticks needed
# [1] 1 2 3
cols1 <- names(df) ## vector of column names
cols1
# [1] "big creek" "gage creek" "garvey creek"
make.names(cols1) ## `make.names` fixes names
# [1] "big.creek" "gage.creek" "garvey.creek"
names(df) <- make.names(cols1)
names(df)
# [1] "big.creek" "gage.creek" "garvey.creek" ## valid names
## actually you don't need to cache in a vector and just may do
names(df) <- make.names(names(df))
From then on, use valid names for coding and label your data separately, e.g.:
barplot(colSums(df), names.arg=c("big creek", "gage creek", "garvey creek"))
That said, if you still want to have your strings surrounded with backticks, you can use sprintf.
sprintf('`%s`', cols)
# [1] "`big creek`" "`gage creek`" "`garvey creek`" "`larches creek`" "`little usable`"
Solution 2:[2]
Maybe something like this:
result <- gsub('^(.{0})(.*)$', '\\1`\\2`', cols)
paste(result, collapse = " ")
output:
1] "`big creek` `gage creek` `garvey creek` `larches creek` `little usable`"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | TarJae |

