I want to return a data.frame from a function if TRUE, else return NA using return(ifelse(condition, mydf, NA))
我想要返回一个data.frame,如果是TRUE,则返回NA使用return(ifelse(条件,mydf, NA))
However, ifelse strips the column names from the data.frame.
但是,ifelse会从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()的一些附加见解:
> 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")
1 个解决方案
#1
15
ifelse
is generally intended for vectorized comparisons, and has side-effects such as these: as it says in ?ifelse
,
ifelse通常用于矢量化比较,并且有如下副作用:如它在?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 ...
所以在这种情况下(test是一个长度为1的向量)它试图将数据帧转换成长度为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 &&
.
作为一般规则,我发现R用户(特别是来自其他编程语言的用户)首先使用if专有,花一些时间来发现ifelse,然后过度使用它一段时间,然后发现在逻辑上下文中确实需要使用if。&和&&也有类似的情况。
See also:
参见:
- section 3.2 of Patrick Burns's R Inferno ...
- 帕特里克·伯恩斯的《地狱》第3.2节……
- Why can't R's ifelse statements return vectors?
- 为什么R的ifelse语句不能返回向量?
#1
15
ifelse
is generally intended for vectorized comparisons, and has side-effects such as these: as it says in ?ifelse
,
ifelse通常用于矢量化比较,并且有如下副作用:如它在?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 ...
所以在这种情况下(test是一个长度为1的向量)它试图将数据帧转换成长度为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 &&
.
作为一般规则,我发现R用户(特别是来自其他编程语言的用户)首先使用if专有,花一些时间来发现ifelse,然后过度使用它一段时间,然后发现在逻辑上下文中确实需要使用if。&和&&也有类似的情况。
See also:
参见:
- section 3.2 of Patrick Burns's R Inferno ...
- 帕特里克·伯恩斯的《地狱》第3.2节……
- Why can't R's ifelse statements return vectors?
- 为什么R的ifelse语句不能返回向量?