I wondered how I can limit a vector of numerics to exact .5 steps. Rounding is not allowed. All values that are not exact multiples of .5 shall be replaced by NA (they are erroneous data entries).
I think my approach of conversion into character with sprintf and using a reprex to identify values that are not .[0|5]0$
is rather straight forward. However, I'm curious about other ideas.
x <- c(seq(0, 1.5, .5), .3, 1.01, 0.53)
x
#> [1] 0.00 0.50 1.00 1.50 0.30 1.01 0.53
## desired output
x[!grepl(".[0|5]0$", sprintf("%.2f", x))] <- NA
x
#> [1] 0.0 0.5 1.0 1.5 NA NA NA
CodePudding user response:
Just having posted it, I realised I could also use %%
x[!x%%.5 == 0] <- NA
x
#> [1] 0.0 0.5 1.0 1.5 NA NA NA
CodePudding user response:
Another possible solution:
ifelse((x-trunc(x)) %in% c(0.0, 0.5), x, NA)
#> [1] 0.0 0.5 1.0 1.5 NA NA NA