英文:
In R use accumulate with nested conditions to set minimum and maximum
问题
我想创建一个新的列 y,该列将 x 添加到先前的 y 值(即 lag(y)),并根据以下条件进行打印。y 的初始值为 50。
- 如果(x + lag(y))大于 50,则打印 50。
- 如果(x + lag(y))在 0 和 50 之间,则打印 x + lag(y)。
- 如果(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.
- If (x + lag(y)) is greater than 50, than print 50.
- If (x + lag(y)) is between 0 and 50, then print x + lag(y).
- 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<-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)
My code satisfying conditions 1 and 2, but not 3.
df %>%
mutate(y = accumulate(x, ~
if((.x + .y) > 50) 50 else .x + .y, .init = 50)[-1])
Desired result
y<-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<-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)
If you have any questions, please write on the comments so I can adjust my reply or explain.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论