R tidyr使用技巧:如何让fill函数填充到最后一个匹配模式行后停止
实现方法
核心逻辑是先定位到((s: End))对应的行号,仅对该行及之前的部分执行向下填充,后续行不填充直接保留NA即可。
完整代码如下:
library(dplyr) library(tidyr) # 原始数据 df <- structure(list(line = c("001", "002", "003", "004", "005", "006", "007", "008", "009", "010", "011", "012", "013", "014"), utterance = c("((m: both hands", "((m: both hands", "((i: DH=1, SZ=0", "((i: DH=1, SZ=0", "((s: Preface))", "((m: both hands", "((m: both hands clasped", "((m: both hands clasped", "((s: Background))", "((m: enumerating", "((m: enumerating", "((s: End))", "((i: DH=1, SZ=0", "((m: relax gesture))" )), row.names = c(NA, 14L), class = "data.frame") # 定位((s: End))所在行号 end_row <- which(df$utterance == "((s: End))") df %>% # 生成初始story列,匹配((s的行保留原值,其余为NA mutate(story = ifelse(grepl("\\(\\(s", utterance), utterance, NA)) %>% # 取End行及之前的部分做向下填充 slice(1:end_row) %>% fill(story, .direction = "down") %>% # 拼接End行之后的内容,story列默认补NA bind_rows(df %>% slice(-(1:end_row)))
运行后输出结果和预期完全一致:
line utterance story 1 001 ((m: both hands <NA> 2 002 ((m: both hands <NA> 3 003 ((i: DH=1, SZ=0 <NA> 4 004 ((i: DH=1, SZ=0 <NA> 5 005 ((s: Preface)) ((s: Preface)) 6 006 ((m: both hands ((s: Preface)) 7 007 ((m: both hands clasped ((s: Preface)) 8 008 ((m: both hands clasped ((s: Preface)) 9 009 ((s: Background)) ((s: Background)) 10 010 ((m: enumerating ((s: Background)) 11 011 ((m: enumerating ((s: Background)) 12 012 ((s: End)) ((s: End)) 13 013 ((i: DH=1, SZ=0 <NA> 14 014 ((m: relax gesture)) <NA>
内容的提问来源于stack exchange,提问作者Chris Ruehlemann
相关产品推荐
相关产品推荐

