Valentas
Valentas

Reputation: 2245

Does R ifelse work correctly with empty vectors?

I would expect ifelse function to return an empty vector of the same type as its second or third argument, as per the documentation:

Value:

A vector of the same length and attributes (including dimensions and ‘"class"’) as ‘test’ and data values from the values of ‘yes’ or ‘no’. The mode of the answer will be coerced from logical to accommodate first any values taken from ‘yes’ and then any values taken from ‘no’.

However it returns logical(0) in the case when all vectors are empty, regardless of the type of the second and third arguments (R version 3.3.2).

> ifelse(logical(), numeric(), numeric())
logical(0)

Is this a bug? If yes, how do I report it and is there any chance it is fixed?

My use case was my own function for replacing NAs with arbitrary values

rep_nan<-function(x, value=0) ifelse(is.na(x), value, x)

however the mentioned inconsistency causes type issues, for example, when working with data.table.

Upvotes: 2

Views: 1550

Answers (1)

coletl
coletl

Reputation: 803

In your example, ifelse() returns logical(0) not because the empty numeric is being coerced, but because whenever test = logical(0), the result is logical(0).

ifelse(logical(), numeric(), numeric())
# logical(0)

ifelse(0, numeric(), numeric())
# NA

ifelse(logical(), 0, 1)
# logical(0)

Even when returning a missing value, the coercion from logical happens as the documentation describes:

class(ifelse(0, numeric(), numeric()))
# "numeric"

Upvotes: 3

Related Questions