[R] Nested ifelse - is there a better way?

Jeff Enos jeff at kanecap.com
Wed Jan 12 00:18:55 CET 2005


Dear r-help,

I'm interested in finding a better way to add a column to a data frame
when calculating the new column requires more than one conditional.

For example, if I wanted to associate a character string in
{"Pos","Neg","Zero"} with each number in the following data frame:

> d <- data.frame(num = -2:2)
> d
  num
1  -2
2  -1
3   0
4   1
5   2

I could use a nested ifelse:

> d$p1 <- ifelse(d$num < 0, "Neg", ifelse(d$num == 0, "Zero", "Pos"))
> d
  num   p1
1  -2  Neg
2  -1  Neg
3   0 Zero
4   1  Pos
5   2  Pos

which I believe becomes cumbersome if more conditionals are required.
I've also considered using sapply:

> d$p2 <- sapply(d$num, function(num) { if (num < 0) { "Neg" } else if (num == 0) { "Zero" } else { "Pos" } })
> d
  num   p1   p2
1  -2  Neg  Neg
2  -1  Neg  Neg
3   0 Zero Zero
4   1  Pos  Pos
5   2  Pos  Pos

Is there a more elegant approach to situations like this?

Thanks in advance,

Jeff




More information about the R-help mailing list