Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Determine if a variable is a string

Is there a way to determine if an R variable is a single string? is.character looked promising, but there was one issue: is.character(c("a", "b")) also returned TRUE which is not what I want.

like image 794
jamesatha Avatar asked Jul 14 '16 23:07

jamesatha


People also ask

How do I check if a variable is a string in R?

character() Function in R Language is used to check if the object is of the form of a string/character or not. It will return true if any element of the object is of the character data type.

How do you check if a variable is a string?

Use the typeof operator to check if a variable is a string, e.g. if (typeof variable === 'string') . If the typeof operator returns "string" , then the variable is a string. In all other cases the variable isn't a string. Copied!

How do you test if a character is in a string in R?

In R, we use the grepl() function to check if characters are present in a string or not. And the method returns a Boolean value, TRUE - if the specified sequence of characters are present in the string.


2 Answers

Based on the comments, this is my current solution:

isSingleString <- function(input) {
    is.character(input) & length(input) == 1
}
like image 179
jamesatha Avatar answered Sep 20 '22 02:09

jamesatha


Try is.string() function from assertthat package.

like image 44
jjankowiak Avatar answered Sep 21 '22 02:09

jjankowiak