[英]dplyr: if_else is greedy
I am trying to mutate
a new variable conditionally on the value of another variable using if_else
, but if_else
insists on computing all the values, and then conditionally replacing the values in the final vector. 我试图使用
if_else
在另一个变量的值上有条件地mutate
一个新变量,但if_else
坚持计算所有值,然后有条件地替换最终向量中的值。
This behaviour is problematic when the function that results in the final values for some cases cannot be computed for other cases: 当导致某些情况的最终值的函数无法针对其他情况计算时,此行为是有问题的:
df_foo = data_frame(
rate = sample(c(0, 0.1), size = 100, replace = TRUE),
pmt = 1000,
nper = 10
)
df_foo %>%
mutate(
if_else(
rate > 0,
optiRum::PV(rate = rate, pmt = -pmt, nper = nper),
0
)
)
Is there any way to only compute the TRUE
values when the condition is TRUE
? 有没有办法只在条件为
TRUE
时计算TRUE
值?
This is not a problem specific to if_else
, the base version ifelse
acts the same. 这不是
if_else
特有的问题,基本版本ifelse
行为相同。 From the help file of ifelse
we can read: 从
ifelse
的帮助文件中我们可以读到:
If
yes
orno
are too short, their elements are recycled.如果
yes
或no
太短,其元素将被回收。yes
will be evaluated if and only if any element oftest
is true, and analogously forno
.yes
会进行评估,当且仅当任何元素test
是真实的,类似的no
。
There is a number of cases where ifelse
use is inappropriate, and the raising of warnings of errors in one of the conditions is one. 在许多情况下,使用
ifelse
是不合适的,并且在其中一个条件中引发错误警告是一个。
A solution to do what you want (without dplyr
) is: 做你想要的解决方案(没有
dplyr
)是:
df_foo$x <- 0
df_foo$x[df_foo$rate > 0] <- with(df_foo[df_foo$rate > 0, ], optiRum::PV(rate, nper, -pmt))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.