简体   繁体   English

dplyr:if_else很贪心

[英]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 or no are too short, their elements are recycled. 如果yesno太短,其元素将被回收。 yes will be evaluated if and only if any element of test is true, and analogously for no . 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM