ifelse为什么将data.frame转换为列表:ifelse(TRUE,data.frame(1),0))!= data.frame(1)? [英] Why does ifelse convert a data.frame to a list: ifelse(TRUE, data.frame(1), 0)) != data.frame(1)?
问题描述
如果要为TRUE,我想从函数返回data.frame,否则使用 return(ifelse(condition,mydf,NA))
I want to return a data.frame from a function if TRUE, else return NA using return(ifelse(condition, mydf, NA))
但是,ifelse从data.frame中删除列名。
However, ifelse strips the column names from the data.frame.
为什么这些结果不同?
> data.frame(1)
X1
1 1
> ifelse(TRUE, data.frame(1), NA)
[[1]]
[1] 1
dput()的一些其他见解:
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")
推荐答案
ifelse
通常用于向量化比较,并具有诸如此类的副作用:如?ifelse
,
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’ ...
因此在这种情况下( test
是长度为1的向量),它尝试将数据帧转换为向量 (在这种情况下为列表)长度为1 ...
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)
作为一般规则,我发现R用户(尤其是来自其他编程语言的用户)首先以独占方式使用 if
,花点时间发现 ifelse
,然后过度使用一段时间,稍后再发现真的想在逻辑上下文中使用 if
。 &
和&
也会发生类似的情况。
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 &&
.
另请参见:
- Patrick Burns的 R地狱 ...
- 为什么R的ifelse语句不能返回矢量?
- section 3.2 of Patrick Burns's R Inferno ...
- Why can't R's ifelse statements return vectors?
这篇关于ifelse为什么将data.frame转换为列表:ifelse(TRUE,data.frame(1),0))!= data.frame(1)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!