我将TSV文件导入R但是某些标签位于错误的位置。例如,我想:
Name Appointment
John Doe 12:30
Jane Doe 1:00
Rick Smith 11:45
Susy Smith 10:15
但我得到
Name Appointment
John Doe 12:30
Jane Doe 1:00
Rick Smith 11:45
Susy Smith 10:15
由于用户错误,没有真正的模式。我已经开发了一个使用substr()的工作来提取约会时间,但后来我失去了姓氏。
我也试过
separate(Data, col = Appointment, c("last", "time"), " ")
并从那里开始工作,但这并不起作用,因为姓氏和时间之间的空格数是可变的,格式不一致:
Name Last Time
John Doe 12:30
Jane Doe 1:00
Rick Smith 11:45
Susy Smith
对不起,如果这是一个愚蠢的问题!
答案 0 :(得分:4)
我们可以使用readLines
阅读此内容,更改分隔符,然后使用read.csv
df1 <- read.csv(text=sub("([a-z])\\s+([0-9])", "\\1, \\2", lines[-1]),
header = FALSE, col.names = strsplit(lines[1], "\\s+")[[1]], stringsAsFactors = FALSE)
要删除&#39;名称&#39;中的多余空格,请使用gsub
df1$Name <- gsub("\\s+", " ", df1$Name)
给我们输出
df1
# Name Appointment
#1 John Doe 12:30
#2 Jane Doe 1:00
#3 Rick Smith 11:45
#4 Susy Smith 10:15
lines <- readLines("file.txt")