R - 条件滞后 - 如何滞后一定数量的细胞直到满足条件?

R - Conditional lagging - How to lag a certain amount of cells until a condition is met?

几周来一直试图解决这个问题,但似乎无法解决。

我有以下数据框:

    post_id user_id
1    post-1   user1
2    post-2   user2
3 comment-1   user1
4 comment-2   user3
5 comment-3   user4
6    post-3   user2
7 comment-4   user2

并想创建一个新变量parent_id。因此对于每个观察,它应该执行以下步骤:

  1. 检查 post_idpost 还是 comment
  2. 如果post_idpost那么parent_id应该等于整个数据帧中最早的post_id
  3. 如果 post_id 是第一个 post 那么 parent_id 应该等于 NA
  4. 如果 post_idcomment 那么 parent_id 应该等于它遇到的第一个 post_id

输出应该类似于:

    post_id user_id parent_id_man
1    post-1   user1            NA
2    post-2   user2        post-1
3 comment-1   user1        post-2
4 comment-2   user3        post-2
5 comment-3   user4        post-2
6    post-3   user2        post-1
7 comment-4   user2        post-3

我试过以下方法:

#Prepare data
df <- df %>% separate(post_id, into=c("type","number"), sep="-", remove=FALSE)
df$number <- as.numeric(df$number)
df <- df %>% mutate(comment_number = ifelse(type == "comment",number,99999))
df <- df %>% mutate(post_number = ifelse(type == "post",number,99999))

#Create parent_id column
df <- df %>% mutate(parent_id = ifelse(type == "post",paste("post-",min(post_number), sep=""),0))
df <- df %>% mutate(parent_id = ifelse(parent_id == post_id,"NA",parent_id))
df <- df %>% select(-comment_number, -post_number)

使用该代码我可以执行步骤 1、2 和 3,但是 步骤 4 超出了我的范围。我觉得基于某种类型的条件滞后应该能够解决它,但无法想出如何去做。

任何想法将不胜感激!

以您的解决方案为基础,

x <- which(df$type == 'post')
z <- which(df$type == 'comment')
df$parent_id[df$parent_id == 0] <- df$post_id[x[sapply(z, function(i) findInterval(i, x))]]
df$parent_id
#[1] "NA"     "post-1" "post-2" "post-2" "post-2" "post-1" "post-3"