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

我有一个列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

相关文章

jquery.validate使用攻略(表单校验) 目录 jquery.validate...
/\s+/g和/\s/g的区别 正则表达式/\s+/g...
自整理几个jquery.Validate验证正则: 1. 只能输入数字和字母...
this.optional(element)的用法 this.optional(element)是jqu...
jQuery.validate 表单动态验证 实际上jQuery.validate提供了...
自定义验证之这能输入数字(包括小数 负数 ) &lt;script ...