我们可以看这个使用readLines
,然后使用sub
#read the lines with readLines
lines <- readLines('pavel.txt')
#match one or more spaces followed by one or more characters
#replace with `''` to extract the non-space characters at the beginning.
str1 <- sub('\\s+.*', '', lines)
#match non space characters from the beginning (`^[^ ]+`) followed by space
#replace with `''` to extract the characters that follow after the space.
str2 <- sub('^[^ ]+\\s+', '', lines)
out <- data.frame(v1= str1, v2=str2, stringsAsFactors=FALSE)
head(out,3)
# v1 v2
#1 LIISS License Issued
#2 LIMOD License Modified
#3 LIPASS License Assigned (Partial Assignment)
创建一个两列data.frame
或者另一种选择读取数据集作为一列,在从library(tidyr)
extract
。我们使用捕获组来提取每列中所需的字符。这里的([^ ]+)
匹配一个或多个非空格,并用圆括号捕捉,后面跟着一个或多个空格(我们删除),然后使用第二个捕获组来提取其余字符。
library(tidyr)
extract(read.table('pavel.txt', sep=','), V1,
into= c('V1', 'V2'), '([^ ]+)\\s+(.*)')
# V1 V2
#1 LIISS License Issued
#2 LIMOD License Modified
#3 LIPASS License Assigned (Partial Assignment)
#4 LIPND License Assigned (Partition/Disaggregation)
#5 LIPPND License Issued from a Partial/P&D Assignment
#6 LIPUR License Purged
#7 LIREIN License Reinstated
#8 LIREN License Renewed
或者,我们可以更换,
第一空间,然后使用read.csv
与sep=','
。
read.table(text=sub(' ', ',', readLines('pavel.txt')), sep=',')
# V1 V2
#1 LIISS License Issued
#2 LIMOD License Modified
#3 LIPASS License Assigned (Partial Assignment)
#4 LIPND License Assigned (Partition/Disaggregation)
#5 LIPPND License Issued from a Partial/P&D Assignment
#6 LIPUR License Purged
#7 LIREIN License Reinstated
#8 LIREN License Renewed
如果我们正在使用Linux,那么awk
可以用fread
从data.table
或read.csv/read.table
管道。
library(data.table)
fread("awk '{sub(\" \", \",\", $0)}1' pavel.txt", header=FALSE)
# V1 V2
#1: LIISS License Issued
#2: LIMOD License Modified
#3: LIPASS License Assigned (Partial Assignment)
#4: LIPND License Assigned (Partition/Disaggregation)
#5: LIPPND License Issued from a Partial/P&D Assignment
#6: LIPUR License Purged
#7: LIREIN License Reinstated
#8: LIREN License Renewed
后可再现的例子。 –