Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ifelse convert a data.frame to a list: ifelse(TRUE, data.frame(1), 0)) != data.frame(1)?

I want to return a data.frame from a function if TRUE, else return NA using return(ifelse(condition, mydf, NA))

However, ifelse strips the column names from the data.frame.

Why are these results different?

> data.frame(1)   X1 1  1 > ifelse(TRUE, data.frame(1), NA) [[1]] [1] 1 

Some additional insight from dput():

> dput(ifelse(TRUE, data.frame(1), 0)) list(1) > dput(data.frame(1)) structure(list(X1 = 1), .Names = "X1", row.names = c(NA, -1L),            class = "data.frame") 
like image 231
David LeBauer Avatar asked Jun 10 '11 18:06

David LeBauer


People also ask

What does Ifelse mean in R?

R ifelse() Function In R, the ifelse() function is a shorthand vectorized alternative to the standard if...else statement. Most of the functions in R take a vector as input and return a vectorized output. Similarly, the vector equivalent of the traditional if...else block is the ifelse() function.

How do I create a new data frame in R?

How to Create a Data Frame. We can create a dataframe in R by passing the variable a,b,c,d into the data. frame() function. We can R create dataframe and name the columns with name() and simply specify the name of the variables.


1 Answers

ifelse is generally intended for vectorized comparisons, and has side-effects such as these: as it says in ?ifelse,

‘ifelse’ returns a value with the same shape as ‘test’ ... 

so in this case (test is a vector of length 1) it tries to convert the data frame to a 'vector' (list in this case) of length 1 ...

return(if (condition) mydf else NA) 

As a general design point I try to return objects of the same structure no matter what, so I might prefer

if (!condition) mydf[] <- NA return(mydf) 

As a general rule, I find that R users (especially coming from other programming languages) start by using if exclusively, take a while to discover ifelse, then overuse it for a while, discovering later that you really want to use if in logical contexts. A similar thing happens with & and &&.

See also:

  • section 3.2 of Patrick Burns's R Inferno ...
  • Why can't R's ifelse statements return vectors?
like image 163
Ben Bolker Avatar answered Oct 12 '22 23:10

Ben Bolker