0

I create a data.table like this:

dd<-data.table(c(7,8,9),c(10,5,10),c(8,9,11))

I then try to pass it a function using := but I get condition has length > 1 error.

dd[,Cat:= as.factor(if(V1 > V2 & V2 > V3) 
{"decrease,decrease"} else if(V1 > V2 & V2 < V3)
{"decrease,increase"} else if(V1 < V2 & V2 < V3)
{"increase,increase"} else if(V1 < V2 & V2 > V3)
{"increase,decrease"})]

I know this is because this is how if works. I could do something like the following if I only had two columns:

dd[, Cat:= as.factor(ifelse(V1>V2, "increase", "decrease"))]

Which works because ifelse is apparently vectorized. But I have three different outputs I would like to produce, not two.

Maxwell Chandler
  • 626
  • 8
  • 18
  • 1
    You could also work on subsets in stead. e.g., `dd[V1 > V2 & V2 > V3, Cat := {"decrease,decrease"}]` in order to avoid `if` statements/nesting all together. – David Arenburg Oct 09 '17 at 17:03

1 Answers1

2

You can nest ifelse,

ifelse(V1 > V2 & V2 > V3, "decrease,decrease",
    ifelse(V1 > V2 & V2 < V3, "decrease,increase",
        ifelse(...)))

But in this case I would probably do paste(ifelse(V1 < V2, "increase", "decrease"), ifelse(V2 < V3, "increase", "decrease"), sep = ",") so I didn't have to write out every combination.

See alse Alternatives to nested ifelse and nested ifelse statement in R.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294