I try to add single quotes to a string but don't see how to do it. For instance I would like to replace ABC by 'ABC'.
I have played with paste, cat, print but don't see how to do it.
Any solution?
Thanks,
Vincent
Maybe use sQuote?
sQuote("ABC")
# [1] "'ABC'"
This (like its sibling dQuote) is frequently used to put quotes around some message or other text that's being printed to the console:
cat("ABC", "\n")
# ABC
cat(sQuote("ABC"), "\n")
# 'ABC'
Do note (as is documented in ?sQuote) that, depending on the type of quotes needed for your task, you may need to first reset options("useFancyQuotes"). To ensure that the function decorates your text with simple upright ASCII quotes, for example, do the following:
options(useFancyQuotes = FALSE)
sQuote("ABC")
# [1] "'ABC'"
Just use paste:
R> paste("'", "ABC", "'", sep="")
[1] "'ABC'"
or the new variety
R> paste0("'", "ABC", "'")
[1] "'ABC'"
Extending #vodka answer:
s <- c("cat", "dog")
a <- "'"
mapply(paste0, a, s, a)
Using Reduce and paste0
Reduce(paste0,list("'","a","'"))
[1] "'a'"
Maybe I'm missing something:
s <- "cat"
a <- "'"
paste(a,s,a,sep="")
Related
The string is as shown below:
s <- "12N10-3A 12N10-3A-1 12N10-3A-2 YB10L-A2"
I can get the strings except from second one.
gsub("\\s.*","",s) #12N10-3A
gsub(".*\\s","",s) #YB10L-A2
gsub(".*\\s.*\\s(.*).*\\s(.*)","\\1",s) #12N10-3A-2
How to get the second string from s and what's short approach for each code line? I tried what I learnt on regex101.com
We can use stri_extract_last from stringi
library(stringi)
stri_extract_last(s, regex = '\\S+')
#[1] "YB10L-A2"
Or use word from stringr
library(stringr)
word(s, 4)
#[1] "YB10L-A2"
Just use strsplit:
items <- strsplit(s, "\\s+")[[1]]
If you want to access the last item, then just use:
items[4]
[1] "YB10L-A2"
If you really wanted to isolate the last term using sub, then here is one way:
sub(".*\\s+", "", s)
Looking for some guidance on how to replace a curly apostrophe with a straight apostrophe in an R list of character vectors.
The reason I'm replacing the curly apostrophes - later in the script, I check each list item, to see if it's found in a dictionary (using qdapDictionary) to ensure it's a real word and not garbage. The dictionary uses straight apostrophes, so words with the curly apostrophes are being "rejected."
A sample of the code I have currently follows. In my test list, item #6 contains a curly apostrophe, and item #2 has a straight apostrophe.
Example:
list_TestWords <- as.list(c("this", "isn't", "ideal", "but", "we", "can’t", "fix", "it"))
func_ReplaceTypographicApostrophes <- function(x) {
gsub("’", "'", x, ignore.case = TRUE)
}
list_TestWords_Fixed <- lapply(list_TestWords, func_ReplaceTypographicApostrophes)
The result: No change. Item 6 still using curly apostrophe. See output below.
list_TestWords_Fixed
[[1]]
[1] "this"
[[2]]
[1] "isn't"
[[3]]
[1] "ideal"
[[4]]
[1] "but"
[[5]]
[1] "we"
[[6]]
[1] "can’t"
[[7]]
[1] "fix"
[[8]]
[1] "it"
Any help you can offer will be most appreciated!
This might work: gsub("[\u2018\u2019\u201A\u201B\u2032\u2035]", "'", x)
I found it over here: http://axonflux.com/handy-regexes-for-smart-quotes
You might be running up against a bug in R on Windows. Try using utf8::as_utf8 on your input. Alternatively, this also works:
library(utf8)
list_TestWords <- as.list(c("this", "isn't", "ideal", "but", "we", "can’t", "fix", "it"))
lapply(list_TestWords, utf8_normalize, map_quote = TRUE)
This will replace the following characters with ASCII apostrophe:
U+055A ARMENIAN APOSTROPHE
U+2018 LEFT SINGLE QUOTATION MARK
U+2019 RIGHT SINGLE QUOTATION MARK
U+201B SINGLE HIGH-REVERSED-9 QUOTATION MARK
U+FF07 FULLWIDTH APOSTROPHE
It will also convert your text to composed normal form (NFC).
I see a problem in your call to gsub:
gsub("/’", "/'", x, ignore.case = TRUE)
You are prefixing the curly single quote with a forward slash. I don't know why you are doing this. I could speculate that you are trying to escape the quote characters, but this is having the side effect that your pattern is now trying to match a forward slash followed by a quote. As this never occurs in your text, no replacements are being made. You should be doing this:
gsub("’", "'", x, ignore.case = TRUE)
Follow the link below for a demo which shows that using the above gsub calls works as you expect.
Demo
Was about to say the same thing.
Try using str_replace from stringr package, will not need to use slashes
I was facing similar problem. Somehow non of the solutions worked for me. So I devised an indirect way of doing it by identifying apostrophe and replacing it with the required format.
gsub("(\\w)(\\W)(\\w\\s)", "\\1'\\3","sid’s bicycle")
[1] "sid's bicycle"
Hope it helps someone.
In excel (and Excel VBA) it is really helpful to connect text and variable using "&":
a = 5
msgbox "The value is: " & a
will give
"The value is: 5"
How can I do this in R? I know there is a way to use "paste". However I wonder if there isn't any trick to do it as simple as in Excel VBA.
Thanks in advance.
This blog post suggests to define your own concatenation operator, which is similar to what VBA (and Javascript) has, but it retains the power of paste:
"%+%" <- function(...) paste0(..., sep = "")
"Concatenate hits " %+% "and this."
# [1] "Concatenate hits and this."
I am not a big fan of this solution though because it kind of obscures what paste does under the hood. For instance, is it intuitive to you that this would happen?
"Concatenate this string " %+% "with this vector: " %+% 1:3
# [1] "Concatenate this string with this vector: 1"
# [2] "Concatenate this string with this vector: 2"
# [3] "Concatenate this string with this vector: 3"
In Javascript for instance, this would give you Concatenate this string with this vector: 1,2,3, which is quite different. I cannot speak for Excel, but you should think about whether this solution is not more confusing to you than it is useful.
If you need Javascript-like solution, you can also try this:
"%+%" <- function(...) {
dots = list(...)
dots = rapply(dots, paste, collapse = ",")
paste(dots, collapse = "")
}
"Concatenate this string " %+% "with this string."
# [1] "Concatenate this string with this string."
"Concatenate this string " %+% "with this vector: " %+% 1:3
# [1] "Concatenate this string with this vector: 1,2,3"
But I haven't tested extensively, so be on lookout for unexpected results.
Another possibility is to use sprintf:
a <- 5
cat(sprintf("The value is %d\n",a))
## The value is 5
the %d denotes integer formatting (%f would give "The value is 5.000000"). The \n denotes a newline at the end of the string.
sprintf() can be more convenient than paste or paste0 when you want to put together a lot of pieces, e.g.
sprintf("The value of a is %f (95% CI: {%f,%f})",
a_est,a_lwr,a_upr)
I have a basic problem in R, everything I'm working with is familiar to me (data, functions) but for some reason I can't get the strsplit or the gsub function to work as expected. I also tried the stringr package. I'm not going to bother putting up code using that package because I know this problem is simple and can be done with the two functions mentioned above. Personally, I feel like putting up a page for this isn't even necessary but my patience is pretty thin at this point.
I am trying to remove the "." and the number followed by the '.' in an Ensemble Gene ID. Simple, I know.
id <- "ENSG00000223972.5"
gsub(".*", "", id)
strsplit(id, ".")
The asterisk symbol was meant to catch anything after the '.' and remove it but I don't know for sure if that's what it does. The strsplit should definitely output a list of two items, the first being everything before the '.' and the second being the one digit after. All it returns is a list with 17 "" symbols, for no space and one for each character in the string. I think it's an obvious thing that I'm missing but I haven't been able to figure it out. Thanks in advance.
Read the help file for ?strsplit, you cannot use "."
id <- "ENSG00000223972.5"
gsub("[.]", "", id)
strsplit(id, split = "[.]")
Output:
> gsub("[.]", "", id)
[1] "ENSG000002239725"
> strsplit(id, split = "[.]")
[[1]]
[1] "ENSG00000223972" "5"
Help:
unlist(strsplit("a.b.c", "."))
## [1] "" "" "" "" ""
## Note that 'split' is a regexp!
## If you really want to split on '.', use
unlist(strsplit("a.b.c", "[.]"))
## [1] "a" "b" "c"
## or
unlist(strsplit("a.b.c", ".", fixed = TRUE))
Referring the title, I'm figuring how to convert space between words to be %20 .
For example,
> y <- "I Love You"
How to make y = I%20Love%20You
> y
[1] "I%20Love%20You"
Thanks a lot.
Another option would be URLencode():
y <- "I love you"
URLencode(y)
[1] "I%20love%20you"
gsub() is one option:
R> gsub(pattern = " ", replacement = "%20", x = y)
[1] "I%20Love%20You"
The function curlEscape() from the package RCurl gets the job done.
library('RCurl')
y <- "I love you"
curlEscape(urls=y)
[1] "I%20love%20you"
I like URLencode() but be aware that sometimes it does not work as expected if your url already contains a %20 together with a real space, in which case not even the repeated option of URLencode() is doing what you want.
In my case, I needed to run both URLencode() and gsub consecutively to get exactly what I needed, like so:
a = "already%20encoded%space/a real space.csv"
URLencode(a)
#returns: "encoded%20space/real space.csv"
#note the spaces that are not transformed
URLencode(a, repeated=TRUE)
#returns: "encoded%2520space/real%20space.csv"
#note the %2520 in the first part
gsub(" ", "%20", URLencode(a))
#returns: "encoded%20space/real%20space.csv"
In this particular example, gsub() alone would have been enough, but URLencode() is of course doing more than just replacing spaces.