I have following data frame:
> ddf = data.frame(name=c('a','b'), value=c(10,20))
> ddf
name value
1 a 10
2 b 20
I try to get xx from ddf using following command:
> xx = ddf[ddf$name=='a','value']
> xx
[1] 10
> xx = ddf[ddf$name=='c','value']
> xx
numeric(0)
How can I test if xx is a valid number and not 'numeric(0)'. I tried following:
> is.numeric(xx)
[1] TRUE
> is.na(xx)
logical(0)
> is.null(xx)
[1] FALSE
> is.logical(xx)
[1] FALSE
I have to ask for xx = ddf[ddf$name=='a', 'value']
from different ddf
data frames. Sometimes ddf
does not contain 'a'
and hence no value is returned. I want to detect this.
We can check if our vector is numeric by using the function is. numeric() . We can check our data type by using the functions class() and typeof() . class() tells us that we're working with numeric values, while typeof() is more specific and tells us we're working with doubles (i.e., numbers with decimals).
We can use select_if() function to get numeric columns by calling the function with the dataframe name and isnumeric() function that will check for numeric columns.
A variable in R can store an atomic vector, group of atomic vectors or a combination of many Robjects. A valid variable name consists of letters, numbers and the dot or underline characters. The variable name starts with a letter or the dot not followed by a number.
The easiest way to do this using base R is to check the length of xx
.
if(length(xx)>0)
{
<do something>
}
If you want to check that the variable is also numeric use is.numeric
if (length(xx)>0 & is.numeric(xx))
For instance, taking your example:
xx <- ddf[ddf$name=='a','value']
is.numeric(xx) & length(xx)>0
[1] TRUE
xx <- ddf[ddf$name=='c','value']
is.numeric(xx) & length(xx)>0
[1] FALSE
xx <- ddf[ddf$name=='a','name']
is.numeric(xx) & length(xx)>0
[1] FALSE
The following code uses regular expressions to confirm that the character string on contains numeric digits and has at least a single digit. See below:
grepl("^[0-9]{1,}$", xx)
Or if you need to deal with negative numbers and decimal places:
grepl("^[-]{0,1}[0-9]{0,}.{0,1}[0-9]{1,}$", xx)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With