如何根据另一个数据帧的 2 列(开始和结束)中指定的范围标记一个数据帧的行?

How can I label rows of one dataframe according to a range specified in 2 columnns (start and end) of another dataframe?

抱歉,如果之前有人问过这个问题 - 我尝试搜索,但我可能不知道要搜索的正确术语。 我有以下格式的数据:

在一个数据帧(话语)中,我的数据集中有话语的开始和结束帧

id <- c(1,1,1,2,2,2,2)
utterance_number <- c(1,2,3,1,2,3,4)
start_frame <- c(20,35,67,10,44,56,72)
end_frame <- c(29,44,72,15,52,69,82)

utterances <- cbind(id, utterance_number, start_frame, end_frame)
utterances

在另一个数据框中我有所有的帧

id <- c(rep(1,80), rep(2,90))
frame <- c(seq(1:80), seq(1:90))
val1 <- sample(170)
val2 <- sample(170)

values <- cbind(id, frame, val1, val2)
values

我想用 utterance_number 标记每个帧的值,如果它不是话语的一部分,则用 NA 标记。因此,在值的新列 "Utterance_number" 中,前 19 帧将为 NA,第 20-29 帧将标记为“1”,依此类推。

这样做的最佳方法是什么?

您可以使用 merge 并使用 apply 扩展 utterances

merge(values, do.call(rbind, apply(utterances, 1
  , function(x) cbind(id=x[1], frame=x[3]:x[4], utterance_number=x[2])))
 , all.x=TRUE)
#    id frame val1 val2 utterance_number
#1    1     1  166  138               NA
#2    1     2   54  109               NA
#3    1     3   71  103               NA
#4    1     4    9   48               NA
#...
#17   1    17   32   22               NA
#18   1    18  170  100               NA
#19   1    19   57  112               NA
#20   1    20   45  110                1
#21   1    21   25  148                1
#22   1    22   13   25                1
#...
#28   1    28   56   62                1
#29   1    29  130   47                1
#30   1    30  163   15               NA
#31   1    31  110   64               NA
#...