根据另一列中的过去值标记一列中的一行

时间:2021-05-28 09:12:07

Probably basic, but I'm banging my head against a wall.

可能是基本的,但是我的头撞到墙上了。

Say I have this data table:

假设我有这个数据表:

library(data.table)
df <- data.frame(DaystoPeak = c(2,NA,NA,NA,NA,NA,3,NA,NA,NA,NA,NA), 
                 FlagPeak = c(0,0,1,0,0,0,0,0,0,1,0,0))

df <- data.table(df)

df
 #   DaystoPeak FlagPeak
 #1:          2        0
 #2:         NA        0
 #3:         NA        1
 #4:         NA        0
 #5:         NA        0
 #6:         NA        0
 #7:          3        0
 #8:         NA        0
 #9:         NA        0
 #10:        NA        1
 #11:        NA        0
 #12:        NA        0

Basically what I want to do is generate the second column. I was trying out something like:

基本上我要做的就是生成第二列。我尝试了一些东西,比如:

df <- df[, FlagPeak := 0] 
df <- df[, FlagPeak[.I+2] := ifelse(DaystoPeak == 2, 1, FlagPeak)] 

But it doesn't work... probably a circular reference problem or something. I've tried a few other things but they don't work either :(

但它不工作…可能是一个循环引用问题。我还试过其他一些方法,但都不管用

Eg:

例如:

df <- df[, FlagPeak := ifelse(DaystoPeak == 2, c(0,0,1), FlagPeak)] 

Anyone able to lend a hand?

有人能帮忙吗?

1 个解决方案

#1


2  

I think the comments have a lot of good options. I'd probably do this though:

我认为这些评论有很多好的选择。我可能会这么做:

df[, FlagPeak := 0][DaystoPeak + 1:.N, FlagPeak := 1]

This works because df[NA, FlagPeak := 1] doesn't do anything.

这是因为df[NA, FlagPeak:= 1]不起作用。

#1


2  

I think the comments have a lot of good options. I'd probably do this though:

我认为这些评论有很多好的选择。我可能会这么做:

df[, FlagPeak := 0][DaystoPeak + 1:.N, FlagPeak := 1]

This works because df[NA, FlagPeak := 1] doesn't do anything.

这是因为df[NA, FlagPeak:= 1]不起作用。