使用R中的累积函数和嵌套条件来设置最小和最大值。

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

In R use accumulate with nested conditions to set minimum and maximum

问题

我想创建一个新的列 y,该列将 x 添加到先前的 y 值(即 lag(y)),并根据以下条件进行打印。y 的初始值为 50。

  1. 如果(x + lag(y))大于 50,则打印 50。
  2. 如果(x + lag(y))在 0 和 50 之间,则打印 x + lag(y)。
  3. 如果(x + lag(y))小于 0,则打印 0。

我在满足最后一个条件时遇到了困难。这与此问题有关(https://stackoverflow.com/questions/75654267/in-r-conditional-statement-with-lag-value-and-starting-value)。

可重现的数据

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

我的代码满足条件 1 和 2,但不满足条件 3。

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

期望的结果

y<-c(50, 50, 35, 0, 11, 0)
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 50.

  1. If (x + lag(y)) is greater than 50, than print 50.
  2. If (x + lag(y)) is between 0 and 50, then print x + lag(y).
  3. If (x + lag(y)) is less than 0, than print 0.

I am tripped up on satisfying last condition. This is related to this question (https://stackoverflow.com/questions/75654267/in-r-conditional-statement-with-lag-value-and-starting-value).

Reproducible data

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,-50,11,-12)
 df&lt;-data.frame(date,x)

My code satisfying conditions 1 and 2, but not 3.

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

Desired result

y&lt;-c(50, 50, 35, 0, 11, 0)
data.frame(date,x,y)

答案1

得分: 1

你只需要在你的if语句中为小于零的值添加一个条件。我在你的代码中间用else if做了这个处理。

因此,代码应该是:

library(tidyverse)

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

df %>% 
mutate(y = accumulate(x, ~
if((.x + .y) > 50) 50 else if ((.x + .y) < 0) 0 else .x + .y, .init = 50)[-1])

data.frame(date,x,y)
英文:

You just need to add a condition for the values below zero in your if statement. I did that as an else if in the middle of your code.

Therefore, the code should be:

library(tidyverse)

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,-50,11,-12)
df&lt;-data.frame(date,x)

df %&gt;% 
mutate(y = accumulate(x, ~
if((.x + .y) &gt; 50) 50 else if ((.x + .y) &lt; 0) 0 else .x + .y, .init = 50)[-1])

data.frame(date,x,y)

If you have any questions, please write on the comments so I can adjust my reply or explain.

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

发表评论

匿名网友

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

确定