R如何根据条件读取文本文件

R如何根据条件读取文本文件,r,read.csv,R,Read.csv,我是R的初学者,我有一个大的txt文件,如下所示: 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 UserID Quantity Date 1 123 3 2002-09-06 1 456 2 2005-08-13 1 789 4

我是R的初学者,我有一个大的txt文件,如下所示:

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 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
带“:”的行是itemID,以下行是UserID、Quantity和Date

我想将其读入data.frame,如下所示:

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 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实现吗?或者如何按条件读取此文件

任何帮助都将不胜感激

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())

这里有一个解决方案。这是相当手动的,在这个例子中有很多东西需要解包

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)

separator\u模式,因此,如果您正在从文件中读取,您将像这样更改扫描命令<代码>扫描(file=“tempo\\tempo.txt”,what=character())