-2

I try to convert some columns in data.frame from integer to numeric. And this piece of code works well.

test.data[] <- lapply(test.data, function(x) if(is.integer(x)) as.numeric(x) else x)

But when I use ifelse instead of if...else....The result is nonsense.

test.data[] <- lapply(test.data, function(x) ifelse(is.integer(x), as.numeric(x), x))

Why and what is the exactly difference between if...else and ifelse here? Thanks a lot.

wanglin
  • 121
  • 1
  • 1
  • 7
  • 2
    The help files will tell you the difference. – Rich Scriven May 19 '16 at 16:35
  • The title of this question is different but the explanations are exactly what you are looking for http://stackoverflow.com/questions/9449184/if-else-vs-ifelse-with-lists/9460026#9460026 – Pierre L May 19 '16 at 17:50

1 Answers1

0

ifelse returns a result which is the same length as the first argument in all cases. Thus it will return the first element of x in your example. if-else returns one of two values, based on the single logical value (either a vector of length one, or the first element of a longer vector, with a warning).

> x <- c(1L, 2L, 3L)
> ifelse(is.integer(x), as.numeric(x), x)
[1] 1
> y <- c(1,2,3)
> ifelse(is.integer(y), as.numeric(y), y)
[1] 1

> if (TRUE) {1:10} else {11:20}
[1]  1  2  3  4  5  6  7  8  9 10
> if (FALSE) {1:10} else {11:20}
[1] 11 12 13 14 15 16 17 18 19 20

In your case, if-else is the correct operation, as is.integer works on a vector and returns a logical of length 1.

Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112