Home > Mobile >  How to convert quotes of character elements to be surrounded by backticks instead of quotes in R
How to convert quotes of character elements to be surrounded by backticks instead of quotes in R

Time:02-27

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

CodePudding user response:

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, enter image description here

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`"

CodePudding user response:

You cannot have a vector that contain backtick quoted names. Since you said you are using for loop, you can transform each name to contain the backticks within the for loop using as.name:

as.name(cols[1])
`big creek`

lapply(cols, as.name)
[[1]]
`big creek`

[[2]]
`gage creek`

[[3]]
`garvey creek`

[[4]]
`larches creek`

[[5]]
`little usable`
  • Related