【发布时间】:2022-07-25 18:09:02
【问题描述】:
我有这种类型的数据:
df <- structure(list(Utterance = c("(5.127)", ">like I don't understand< sorry like how old's your mom¿",
"(0.855)", "eh six:ty:::-one=", "(0.101)", "(0.487)", "[((v: gasps)) she said] ~no you're [not?]~",
"[((v: gasps)) she said] ~no you're [not?]~", "~<[NO YOU'RE] NOT (.) you can't go !in!>~",
"(0.260)", "show her [your boobs] next time"),
Q = c(NA, "q_wh", "", "", NA, NA, "q_really", "", "", NA, NA),
Sequ = c(NA, 1L, 1L, 1L, NA, NA, 0L, 0L, 0L, NA, NA)), class = "data.frame", row.names = c(NA, -11L))
我想提取/过滤
-
Sequ的那些行不是NA和 - 前一行(
Sequ是NA)
到目前为止,我的尝试是定义一个获取相关行索引的函数:
QA_sequ <- function(value) {
inds <- which(!is.na(value) & lag(is.na(value)))
sort(unique(c(inds-1, inds)))
}
然后通过索引切出行:
library(dplyr)
df %>%
slice(QA_sequ(Sequ))
Utterance Q Sequ
1 (5.127) <NA> NA
2 >like I don't understand< sorry like how old's your mom¿ q_wh 1
3 (0.487) <NA> NA
4 [((v: gasps)) she said] ~no you're [not?]~ q_really 0
但是,只有前一行和第一行 Sequ 会被过滤。 我想要得到的结果是这样的:
Utterance Q Sequ
1 (5.127) <NA> NA
2 >like I don't understand< sorry like how old's your mom¿ q_wh 1
3 (0.855) 1
4 eh six:ty:::-one= 1
5 (0.487) <NA> NA
6 [((v: gasps)) she said] ~no you're [not?]~ q_really 0
7 [((v: gasps)) she said] ~no you're [not?]~ 0
8 ~<[NO YOU'RE] NOT (.) you can't go !in!>~ 0
编辑:
我想出的解决方案感觉很麻烦:
QA_sequ <- function(value) {
inds <- which(!is.na(value) & lag(is.na(value)))
sort(unique(c(inds-1))) # extract only preceding row!
}
library(dplyr)
df %>%
mutate(id = row_number()) %>%
slice(QA_sequ(Sequ)) %>%
bind_rows(., df %>% mutate(id = row_number()) %>% filter(!is.na(Sequ))) %>%
arrange(id)
【问题讨论】: