R - 从一个文本文件中读取多个数据表

时间:2015-05-22 21:06:27

标签: r parsing

我是R的新手,并试图学习如何阅读下面的文字。我正在使用

data <- read.table("myvertices.txt", stringsAsFactors=TRUE, sep=",")

希望传达&#34; FID ......&#34;应该与他们下面的逗号分隔数字相关联。 我得到的错误是:

  

扫描错误(文件,内容,nmax,sep,dec,quote,skip,nlines,na.strings,:     第13行没有2个元素

我如何阅读以下格式

FID001:
-120.9633,51.8496
-121.42749,52.293
-121.25453,52.3195
FID002:
-65.4794,47.69011
-65.4797,47.0401
FID003:
-65.849,47.5215
-65.467,47.515

类似

FID001 -120.9633  51.8496
FID001 -121.42749 52.293
FID001 -121.25453 52.3195
FID002 -65.4794   47.69011
FID002 -65.4797   47.0401
FID003 -65.849    47.5215
FID003 -65.467    47.515

1 个答案:

答案 0 :(得分:1)

以下是实现此目的的可能方法:

data <- read.table("myvertices.txt")            # Read as-is.
fid1 <- c(grep("^FID", data$V1), nrow(data) +1) # Get the row numbers containing "FID.."
df1 <- diff(x = fid1, lag = 1)                  # Calculate the length+1 rows to read
listdata <- lapply(seq_along(df1), 
                   function(n) cbind(FID = data$V1[fid1[n]],
                                     read.table("myvertices.txt", 
                                                skip = fid1[n], 
                                                nrows = df1[n] -1, 
                                                sep = ",")))
data2 <- do.call(rbind, listdata)  # Combine all the read tables into a single data frame.