假设我们有这个文件someFile,内容为:
date time data
2015-02-28 09:00:00,173 Some data here
2015-02-28 09:10:00,251 Anoter data here
我考虑使用可读表
read.table("someFile", header=T, sep=" ")
我不知道如何将行的末尾("Some data here"字符串)分配给单列
您可以使用readLines
读取文件,将字符串前的空格替换为,
,然后尝试使用read.table
dat1 <- read.table(text=sub('(?<=\d) (?=[A-Za-z])', ',',
lines[-1], perl=TRUE), header=FALSE, stringsAsFactors=FALSE, sep=",")
colnames(dat1) <- c('datetime', 'Val', 'Col2')
dat1
# datetime Val Col2
#1 2015-02-28 09:00:00 173 Some data here
#2 2015-02-28 09:10:00 251 Anoter data here
数据
lines <- readLines('SomeFile.txt')
由于您的分隔符不一致(您有"、"one_answers"分隔符),您必须(至少)执行两次。有几个选项,但在我看来,这是最具适应性和可读性的选项:
1) 将整个文件作为字符串列表导入:
datRaw <- readLines("someFile")[[1]]
2) 解析它,手工定义格式。
Parser <- function(line){
initSplit <- strsplit(line,"[ ,]")[[1]]
firstCol <- initSplit[1]
sndCol <- initSplit[2]
thirdCol <- strsplit(line,",")[[1]][2]
return(c(firstCol,sndCol,thirdCol))
}
dat <- as.data.frame(t(sapply(datRaw[-1],Parser)))
names(dat) <- strsplit(datRaw[1]," ")[[1]]
dat
date time
2015-02-28 09:00:00,173 Some data here 2015-02-28 09:00:00
2015-02-28 09:10:00,251 Anoter data here 2015-02-28 09:10:00
data
2015-02-28 09:00:00,173 Some data here 173 Some data here
2015-02-28 09:10:00,251 Anoter data here 251 Anoter data here
首先,您的"data"列似乎使用了空格(因为它是一个字符串)。如果你想支持这一点,你需要将分隔符更改为其他内容,比如逗号:
date,time,number,data
2015-02-28,09:00:00,173,Some data here
2015-02-28,09:10:00,251,Another data here
和:
> read.table(someFile, header=T, sep=",")
现在它读起来是正确的。
您可以使用$column
读取特定列,并使用as.vector
将"数据"列作为向量:
> mydata <- as.vector(read.table(someFile, header=TRUE, sep=",")$data)
> mydata
[1] "Some data here" "Another data here"
> mydata[1]
[1] "Some data here"