如何做多行公式?

How do I do a multirow formula?

我正在尝试使用多行公式来创建一个新的计算列,但我不太明白。

假设我的数据是这样的:

x     y

1     2

1     2

1     6

1     7

2     4

2     5

2     9

我想创建一个计算列 z,其中包含以下逻辑:

如果 x 的值等于 x 的前一个值,则 y-previous(x) 否则为 0。

试试这个:

# load package
library(dplyr)
# reproduce your data
df <- data.frame(x = rep(1:2, c(4, 3)),
                 y = c(2, 2, 6, 7, 4, 5, 9))
df %>%
  mutate(z = case_when(x == lag(x) ~ y - lag(x),
                       TRUE ~ 0))

希望对您有所帮助

或者在 base R 中,这可以用 ifelse

完成
df$z <- c(0, ifelse(diff(df$x) == 0, 1, 0)*(df$y[-1]-df$x[-nrow(df)]))
#   x y z
# 1 1 2 0
# 2 1 2 1
# 3 1 6 5
# 4 1 7 6
# 5 2 4 0
# 6 2 5 3
# 7 2 9 7

数据

df <- structure(list(x = c(1L, 1L, 1L, 1L, 2L, 2L, 2L), y = c(2, 2, 
                                                          6, 7, 4, 5, 9)), class = "data.frame", row.names = c(NA, -7L))

布尔运算与用于构造滞后变量的头部和尾部一起使用。 (第一个实现使用了错误的逻辑):

dat$new <- with(dat, c(0,  # starting value for no prior x
                   tail(y,-1)-head(x, -1)) * #The values if x[-1]==x
              # then construct the x[-1] == x logical vector
                     ( c(0,                        # starting
                   tail(x,-1)== head(x,-1)))) # prior x == current x 

> dat
  x y new
1 1 2   0
2 1 2   1
3 1 6   5
4 1 7   6
5 2 4   0
6 2 5   3
7 2 9   7