微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

正则表达式 – 将某些空格替换为制表符 – 分隔符

我有一个列data.frame,其中一些空格应该分隔一些只是一个空格.
#input data
dat <- data.frame(x=c("A 2 2 textA1 textA2 Z1","B 4 1 textx1 textx2 textx3 Z2","C 3 5 textA1 Z3"))
#                               x
# 1        A 2 2 textA1 textA2 Z1
# 2 B 4 1 textx1 textx2 textx3 Z2
# 3               C 3 5 textA1 Z3

需要将其转换为5列data.frame:

#expected output
output <- read.table(text="
A   2   2   textA1 textA2   Z1
B   4   1   textx1 textx2 textx3    Z2
C   3   5   textA1  Z3",sep="\t")
#   V1 V2 V3                   V4 V5
# 1  A  2  2        textA1 textA2 Z1
# 2  B  4  1 textx1 textx2 textx3 Z2
# 3  C  3  5               textA1 Z3

本质上,需要将第1,第2,第3和最后一个空格更改为标签(或任何其他分隔符,如果它使编码更容易).

使用正则表达式没有给任何有用的东西…

注1:在实际数据中,我必须将第1,第3,…,第19和最后一个空格替换为标签.
注2:V4中没有模式,文本可以是任何东西.
注3:最后一列是长度可变的一个单词文本.

尝试
v1 <- gsub("^([^ ]+)\\s+([^ ]+)\\s+([^ ]+)\\s+",'\\1,\\2,\\3,',dat$x)
read.table(text=sub(' +(?=[^ ]+$)',v1,perl=TRUE),sep=",")
#  V1 V2 V3                   V4 V5
#1  A  2  2        textA1 textA2 Z1
#2  B  4  1 textx1 textx2 textx3 Z2
#3  C  3  5               textA1 Z3

或者选自@ Tensibai的帖子

n <- 3
fpat <- function(n){
   paste0('^((?:\\w+ ){',n,'})([\\w ]+)\\s+(\\w+)$')
}

read.table(text=gsub(fpat(n),"\\1'\\2' \\3",dat$x,perl=TRUE))
#  V1 V2 V3                   V4 V5
#1  A  2  2        textA1 textA2 Z1
#2  B  4  1 textx1 textx2 textx3 Z2
#3  C  3  5               textA1 Z3

对于更多列,

n <- 19
 v1 <- "A 24 34343 212 zea4 2323 12343 111 dsds 134d 153xd 153xe 153de 153dd dd dees eese tees3 zee2 2353 23335 23353 ddfe 3133"

 read.table(text=gsub(fpat(n),sep='')
 # V1 V2    V3  V4   V5   V6    V7  V8   V9  V10   V11   V12   V13   V14 V15
 #1  A 24 34343 212 zea4 2323 12343 111 dsds 134d 153xd 153xe 153de 153dd  dd
 #  V16  V17   V18  V19                   V20  V21
 #1 dees eese tees3 zee2 2353 23335 23353 ddfe 3133

原文地址:https://www.jb51.cc/regex/356689.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐