0

I'm trying to create a factor from vector d that indicates whether each value of d is missing, less than threshhold, or greater than/equal to threshhold. I attempted with the following code, using the cases function from the memisc package.

threshhold = 5
d <- sample(c(1:10, NaN), 50, replace=TRUE)
d_case <- cases(
  is.na(d),
  d > threshhold,
  d <= threshhold
)

and got a warning: In cases(is.na(d), d > threshhold, : condition is.na(d) is never satisfied.

I've also tried using assignment operators,

d_case <- cases(
  is.na(d)        -> 0,
  d > threshhold  -> 1,
  d <= threshhold -> 2
)

and got the same warning. I've checked, and d does contain NaN values, which is.na() should be returning as true (and is, when I check it outside of cases). Does anyone know why cases isn't working, or what I can do to get the indicator factor I need?

Empiromancer
  • 3,778
  • 1
  • 22
  • 53
  • 3
    Where are you getting the `cases` function from? That's not part of base R. It would also help to give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output to make it clear what you are trying to accomplish. – MrFlick Oct 21 '15 at 19:33
  • For this simple example you could also use something like `as.numeric(x > threshold)`, adding 1 and then assigning `0` to `NA` elements if you want. – jbaums Oct 21 '15 at 19:38
  • @MrFlick Thanks for that, I've edited my question to show that cases is from memisc, and have included code to generate sample data so that the problem is reproducible. – Empiromancer Oct 21 '15 at 19:43

2 Answers2

0

Look at ?cases according to the documenation you can do it like this

d <- c(-1:3,NA,1:2)
fun <- function(x){
  cases(
    is.na(x)        -> 0,
    x > threshhold  -> 1,
    x <= threshhold -> 2
  )
}
d_case <- fun(d)
d_cases
RmIu
  • 4,357
  • 1
  • 21
  • 24
0

How about:

addNA(as.factor(d>threshold))
....
Levels: FALSE TRUE <NA>
fishtank
  • 3,718
  • 1
  • 14
  • 16