Question on checking values of character variables

The value of the character variable x, is between 59-154 and missing = N/A.

I have tried the following code: stopifnot((df$x >= "59" & df$x <= "154") & is.na(df$x)) as well as the code here: stopifnot((df$x >= "59" & df$x <= "154") | df$x == "N/A")

Both codes return not all true, how do I get a code that is correct?

apples <- 60:155 # assuming range is exclusive; otherwise 59:154
bushel <- 0:200
bucket <- sample(bushel,50)
bag <- as.character(bucket)

assort <- function(x) as.integer(x) %in% apples & !is.na(x)

assort(bag)
#>  [1]  TRUE  TRUE FALSE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE
#> [13] FALSE FALSE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE
#> [25]  TRUE FALSE  TRUE FALSE FALSE FALSE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE
#> [37] FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE
#> [49] FALSE FALSE

bag[which(assort(bag))]
#>  [1] "132" "105" "152" "86"  "115" "131" "66"  "136" "93"  "94"  "81"  "118"
#> [13] "92"  "144" "119" "97"  "126" "78"  "145" "147" "91"  "83"

Hi, Jeryl:
I think that you get this error because you put the numerical values between quotation marks.

x <- 1:10

# work bad
x["2"] 
#> [1] NA

# works fine
x[2]
#> [1] 2

Created on 2021-04-30 by the reprex package (v2.0.0)

Hope it helps.

Greetings.

Hi,
The variable values are in quotation marks and the missing values are in N/A.

Do I have to convert the character values to numeric, in order to check the values?

Question is resolved!

I did the following method and it worked!

stopifnot((df$x >= "59" & df$x <= "154") | is.na(df$x))

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.