我有一个这样的列表:
list <- c("xxx 23 cut", "yyy", "zzz", "www 55 cut", "kkk", "ggg", "yyy", "eee 7 cut", "ccd" )
Run Code Online (Sandbox Code Playgroud)
在这种情况下,搜索模式是"任意数字切割".因此,为了以更好的方式可视化列表,列表具有以下模式
"before item (=xxx) " "any number cut (= 23 cut)"
"after item (=yyy)"
"after item (=zzz)"
"before item (=www) " "any number cut (= 55 cut)"
"after item (=kkk)"
"after item (=ggg)"
"after items (=yyy)"
"before item (=eee) " "any number cut (= 7cut)"
"after item (=cce)"
Run Code Online (Sandbox Code Playgroud)
我想将"之前的项目"放在第1列,直到找到另一个"任意数字切割"模式,然后将"之后的项目"放到第2列.最终结果如下:
xxx yyy
xxx zzz
www kkk
www ggg
www yyy
eee ccd
Run Code Online (Sandbox Code Playgroud)
专家可以教我如何使用R吗?我从以前的stackoverflow消息中学到了R可以搜索固定项目(例如剪切)并将它们分成不同的单元格.这里(对我来说)的挑战是搜索模式正在改变,"切割"一词之前的数字对于它们中的每一个都是不同的.使用R在正确的地方搜索和剪切它的最有效方法是什么?
以下内容适用于您的示例数据:
x <- c("xxx 23 cut", "yyy", "zzz", "www 55 cut", "kkk", "ggg", "yyy", "eee 7 cut", "ccd" )
Run Code Online (Sandbox Code Playgroud)
首先,创建一个用于的regex模式grep:以下模式搜索数字(\ d),后跟空格和单词cut.查看?regexp并?grep了解详情.
cut_pattern <- "\\d* cut"
cut_positions <- grep(cut_pattern, x)
cut_repeat <- c(cut_positions[-1], length(x) + 1) - cut_positions -1
before_items <- rep(x[cut_positions], times=cut_repeat)
after_items <- x[!grepl(cut_pattern, x)]
data.frame(
before = before_items,
after = after_items
)
Run Code Online (Sandbox Code Playgroud)
结果:
before after
1 xxx 23 cut yyy
2 xxx 23 cut zzz
3 www 55 cut kkk
4 www 55 cut ggg
5 www 55 cut yyy
6 eee 7 cut ccd
Run Code Online (Sandbox Code Playgroud)
我将把它作为练习留给你清理第1列中的数据.提示:str_extract在包中使用stringr.你可以参考这个问题:如何在R中使用带有`grep`的引用?有关如何执行此操作的示例.进一步提示,你的模式应该是这样的"(.*) \\d* cut".