2017-05-04 72 views
1

我在R A初学者,我有一个大的txt文件,这样读取文本文件:[R如何根据病情

1: 
123,3,2002-09-06 
456,2,2005-08-13 
789,4,2001-09-20 
2: 
123,5,2003-05-08 
321,1,2004-06-15 
432,3,2001-09-11 

与行“:”是的itemid,下面几行是用户名,数量和日期

我想把它读入data.frame这样的:

itemID UserID Quantity Date 
    1  123 3  2002-09-06 
    1  456 2  2005-08-13 
    1  789 4  2001-09-20 
    2  123 5  2003-05-08 
    2  321 1  2004-06-15 
    2  432 3  2001-09-11 

它可以通过使用read.csv可以实现吗?或者如何通过条件阅读这个文件?

任何帮助将不胜感激。

回答

2

read.table()无法轻松读取此内容。 R预计大部分数据数据都是干净的和矩形的。

您可以通过一堆行读取数据,将这些行操作为更常规的格式,然后使用read.table解析该行。例如,

# Read your data file 
# xx <- readLines("mydatafile.txt") 
# for the sake of a complete example 
xx <- scan(text="1: 
123,3,2002-09-06 
456,2,2005-08-13 
789,4,2001-09-20 
2: 
123,5,2003-05-08 
321,1,2004-06-15 
432,3,2001-09-11", what=character()) 

这读入只是字符串的行。然后你就可以分成不同的小组和项目ID为其他值追加到每行

item_group <- cumsum(grepl("\\d+:", xx)) 
clean_rows <- unlist(lapply(split(xx, item_group), function(x) { 
    item_id = gsub(":$",",", x[1]) 
    paste0(item_id, x[-1]) 
})) 

然后您可以将数据解析成一个data.frame

read.table(text=clean_rows, sep=",", col.names=c("itemID","UserID","Quantity","Date")) 
+0

所以,如果你从文件中读取你会改变像扫描命令所以。 ...........................................。 'scan(file =“tempo \\ tempo.txt”,what = character())' – DashingQuark

+0

谢谢,它可行! – Joe

0

这里有一个解决方案。这是相当手动和有很多在这个例子中解压...

separator_pattern <- "^(\\d+):\\s*$" 
block_text <- out <- NULL 
for(line in readLines(file("~/temp/example.txt"))){ 
    if(grepl(separator_pattern,line)){ 
     if(!is.null(block_text)){ 
      txt <- paste(c(paste0("column",1:3,collapse = ", "), block_text), collapse="\n") 
      tmp <- cbind("block" = block_no, read.csv(textConnection(txt))) 
      out <- rbind(out,tmp) 
     } 
     block_no <- as.numeric(gsub(separator_pattern,"\\1",line)) 
     print(block_no) 
     block_text <- character(0) 
    }else{ 
     block_text <- c(block_text,line) 
    } 
} 
txt <- paste(c(paste0("column",1:3,collapse = ", "), block_text), collapse="\n") 
tmp <- cbind("block" = block_no, read.csv(textConnection(txt))) 
out <- rbind(out,tmp) 

显然,这个假定你的文件位于path.expand("~/temp/example.txt")