我有一个大的时间段数据集,由"开始"和"结束"列定义.有些时期重叠.
我想将所有重叠时间段组合(展平/合并/折叠)以具有一个"开始"值和一个"结束"值.
一些示例数据:
ID start end
1 A 2013-01-01 2013-01-05
2 A 2013-01-01 2013-01-05
3 A 2013-01-02 2013-01-03
4 A 2013-01-04 2013-01-06
5 A 2013-01-07 2013-01-09
6 A 2013-01-08 2013-01-11
7 A 2013-01-12 2013-01-15
Run Code Online (Sandbox Code Playgroud)
期望的结果:
ID start end
1 A 2013-01-01 2013-01-06
2 A 2013-01-07 2013-01-11
3 A 2013-01-12 2013-01-15
Run Code Online (Sandbox Code Playgroud)
我尝试过的:
require(dplyr)
data <- structure(list(ID = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L), class = "factor", .Label = "A"),
start = structure(c(1356998400, 1356998400, 1357084800, 1357257600,
1357516800, 1357603200, 1357948800), tzone = …Run Code Online (Sandbox Code Playgroud) 我有以下数据:
dat <- data.frame(x = c("this is my example text", "and here is my other text example", "my other text is short"),
some_other_cols = c(1, 2, 2))
Run Code Online (Sandbox Code Playgroud)
此外,我有以下模式向量:
my_patterns <- c("my example", "is my", "my other text")
Run Code Online (Sandbox Code Playgroud)
我想实现的是,以消除任何文本my_patterns发生在dat$x。
我尝试了下面的解决方案,但问题是,一旦我从文本中删除第一个模式(此处:“我的示例”),我的解决方案就无法检测到第二个模式的出现(此处:“是我的”) ) 或第三种模式了。
错误的解决方法:
library(tidyverse)
my_patterns_c <- str_c(my_patterns, collapse = "|")
dat_new <- dat %>%
mutate(short_x = str_replace_all(x, pattern = my_patterns_c, replacement = ""))
Run Code Online (Sandbox Code Playgroud)
我想我可以做某事。就像遍历所有模式一样,收集 dat$x 中与我的模式匹配的字符串位置,然后将它们组合成一个范围并从文本中删除该范围。例如,我将列添加到我dat喜欢的数据帧start_pattern_1和end_pattern_1等。因此,对于第一行 1,我得到第一个模式的 9(开始)和 18(结束),第二个模式的 6/10。然后我需要检查是否有任何end …