gpt4 book ai didi

r - 在另一列中的特定值之前和之后标记观察

转载 作者:行者123 更新时间:2023-12-04 23:38:42 28 4
gpt4 key购买 nike

假设我有一个 df:

df <- data.frame(flag = c(rep(0, 20)),
include = c(rep(1, 20)))
df[c(4,8,16), ]$flag <- 1
df

flag include
1 0 1
2 0 1
3 0 1
4 1 1
5 0 1
6 0 1
7 0 1
8 1 1
9 0 1
10 0 1
11 0 1
12 0 1
13 0 1
14 0 1
15 0 1
16 1 1
17 0 1
18 0 1
19 0 1
20 0 1

我想做的是改变 include如果行在行的 +/- 两行内,则标志为 0,其中 flag == 1 .结果将如下所示:
   flag include
1 0 1
2 0 0
3 0 0
4 1 1
5 0 0
6 0 0
7 0 0
8 1 1
9 0 0
10 0 0
11 0 1
12 0 1
13 0 1
14 0 0
15 0 0
16 1 1
17 0 0
18 0 0
19 0 1
20 0 1

我已经想到了一些“创新”(阅读:低效且过于复杂)的方法来做到这一点,但我认为必须有一种我忽略的简单方法。

如果答案是这样的,我可以将其概括为 +/- n,那就太好了。行,因为我有更多的数据,并且希望在 +/- 10 行内进行潜在的搜索...

最佳答案

data.table 的另一种选择:

library(data.table)
n = 2
# find the row number where flag is one
flag_one = which(df$flag == 1)

# find the index where include needs to be updated
idx = setdiff(outer(flag_one, -n:n, "+"), flag_one)

# update include in place
setDT(df)[idx[idx >= 1 & idx <= nrow(df)], include := 0][]

# or as @Frank commented the last step with base R would be
# df$include[idx[idx >= 1 & idx <= nrow(df)]] = 0

# flag include
# 1: 0 1
# 2: 0 0
# 3: 0 0
# 4: 1 1
# 5: 0 0
# 6: 0 0
# 7: 0 0
# 8: 1 1
# 9: 0 0
#10: 0 0
#11: 0 1
#12: 0 1
#13: 0 1
#14: 0 0
#15: 0 0
#16: 1 1
#17: 0 0
#18: 0 0
#19: 0 1
#20: 0 1

放入一个函数:
update_n <- function(df, n) {
flag_one = which(df$flag == 1)
idx = setdiff(outer(flag_one, -n:n, "+"), flag_one)
df$include[idx[idx >= 1 & idx <= nrow(df)]] = 0
df
}

关于r - 在另一列中的特定值之前和之后标记观察,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46230446/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com