英文:
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<-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)
tried and failed
df2<- df %%
mutate(y = if (x+lag(y) > 44169) {
44169}
else {x + lag(y)}
)
y<-c(44169, 44169, 44154, 44142, 44147, 44169)
result<- 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 %>%
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])
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论