在R中,使用滞后值和起始值的条件语句。

huangapple go评论63阅读模式
英文:

In R conditional statement with lag value and starting value

问题

我想创建一个新列y,该列将x添加到上一个y值(即滞后的y)并根据以下条件打印。y的起始值为44169。

如果(x + 滞后的y)大于或等于44169,则打印44169。
如果(x + 滞后的y)小于44169,则打印x + 滞后的y。

我被滞后和如何处理起始值所困扰。以下是数据和期望的结果,感谢您的帮助

date <- seq(as.Date('1968-04-01'), as.Date('1968-09-01'), by='month')
x <- c(20, 10, -15, -12, 5, -50)
df <- data.frame(date, x)

尝试并失败

df2 <- df %>%
  mutate(y = ifelse(x + lag(y) >= 44169, 44169, x + lag(y)))
y <- c(44169, 44169, 44154, 44142, 44147, 44169)
result <- data.frame(date, x, y)
英文:

I want to create a new column y that adds x to previous y value (i.e. lag(y)) and prints based on conditions below. The start value of y is 44169.

if (x + lag(y)) is greater or equal than 44169, than 44169 is printed.
if (x + lag(y)) is less than 44169, then print x + lag(y).

I am tripped up by the lag and how to handle the starting value. Data and desired results are below, Thanks for your help

date&lt;-seq(as.Date(&#39;1968-04-01&#39;),as.Date(&#39;1968-09-01&#39;), by=&#39;month&#39;)
x&lt;-c(20,10,-15,-12,5,-50)
df&lt;-data.frame(date,x)

tried and failed

df2&lt;- df %%
  mutate(y = if (x+lag(y) &gt; 44169) {
      44169}
  else {x + lag(y)}
    )
y&lt;-c(44169, 44169, 44154, 44142, 44147, 44169)
result&lt;- data.frame(date,x,y)

答案1

得分: 2

We may use accumulate

library(dplyr)
library(purrr)
df %>%
  mutate(y = accumulate(x, ~
     if((.x + .y) > 44169) 44169 else .x + .y, .init = 44169)[-1])

Or with pmin/min

df %>%
   mutate(y = accumulate(x, ~ pmin(44169, .x + .y), ..init = 44169)[-1])
英文:

We may use accumulate

library(dplyr)
library(purrr)
df %&gt;% 
  mutate(y = accumulate(x, ~
     if((.x + .y) &gt; 44169) 44169 else .x + .y, .init = 44169)[-1])

Or with pmin/min

df %&gt;%
   mutate(y = accumulate(x, ~ pmin(44169, .x + .y), .init = 44169)[-1])

</details>



huangapple
  • 本文由 发表于 2023年3月7日 02:00:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75654267.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定