r语言 - 在导入表期间可以直接从"t" [原文如此] 分隔符转义吗?



我最近收到一个.txt文件,格式非常不寻常,需要处理:

"Pony ID"/t"colour"/t"location"/t"age"
"Pony A"/t"white;brown;black"/t"stable1"/t12
"Pony B"/t"pink"/t"stable2"/t13
"Pony C"/t"white"/t"stable3"/t9

因此,如果我尝试从utils或readr导入经典的读取函数(例如,read.tsv、read.delim(,我最终会得到1列,可能是因为sep="t〃;输入未被解释为文字分隔符。以下代码解决了这个问题:

library(tidyverse)
a<-read.delim("ponies.txt",sep="/", header = FALSE)
a<-data.frame(cbind(a[,1],sapply(a[,-1], function(x) str_sub(x,2))))
colnames(a)<-a[1,]
a<-a[-1,]
Pony ID            colour location age
2  Pony A white;brown;black  stable1  12
3  Pony B              pink  stable2  13
4  Pony C             white  stable3   9

我希望这个问题不要太晦涩,但我很好奇:有人知道是否有办法直接逃离字面上的"t〃;进口期间的熟食?

在使用read.csv/read.table读取之前,通过使用readLines读取,使用gsub更改分隔符,可以使其更加紧凑

read.csv(text = gsub("/t", ",", gsub('"', '', readLines("ponies.txt"))), 
check.names = FALSE)

-输出

Pony ID            colour location age
1  Pony A white;brown;black  stable1  12
2  Pony B              pink  stable2  13
3  Pony C             white  stable3   9

最新更新