2016-01-16 37 views
0

這裏讀取多行的數據模式是文件圖案R:從文件

metastring: time1, a,b,c,d,f 
144135 42435 345425 2342423 
263766 35553 353453 3534553 
355345 52454 525252 2423465 
245466 45645 355345 6454556 
355662 26397 353577 3558676 
metastring: time2, a,c,d,f 
224234 23423 324234 4242324 
312323 13123 312312 1312321 
246456 63564 646544 4456456 
244424 53556 546456 4645645 

metastrings包括時間戳和A,B,C,d的被名參照號碼的字符串(例如「一」指的是塊的第一個數字串)。數字字符串是固定寬度的,但數量不是恆定的,取決於元字符串。 我要的是無論是結構化的這樣一個data.frame:

time1 a 144135 42435 345425 2342423 
time1 b 263766 35553 353453 3534553 
time1 c 355345 52454 525252 2423465 
time1 d 245466 45645 355345 6454556 
time1 f 355662 26397 353577 3558676 
time2 a 224234 23423 324234 4242324 
time2 c 312323 13123 312312 1312321 
time2 d 246456 63564 646544 4456456 
time2 f 244424 53556 546456 4645645 

或者能夠通過匹配metastring格式和兩個metastrings之間只是念臺詞,在一次單塊讀。找不到一種方法來做到這一點,因爲gsubfn read.pattern似乎一次只讀一行文件,而且我無法獲得比metastring更多的東西。

回答

2

要獲取數據幀作爲回報,可能會使用readLines(),然後對字符串進行一些後處理。在您的代碼中,將textConnection(text)替換爲您的文件的名稱。

## read the file 
dat <- readLines(textConnection(text)) 
## find the 'metastring' lines 
meta <- grepl("metastring", dat, fixed = TRUE) 
## split the 'metastring' lines for the first two columns 
## then create the first two columns 
f2cols <- do.call(
    "rbind", 
    lapply(
     strsplit(dat[meta], "(.*:)|, ?"), 
     function(x) cbind(text1 = x[2], text2 = tail(x, -2)) 
    ) 
) 
## create the final data frame 
cbind(f2cols, read.table(text = dat[!meta])) 
# text1 text2  V1 V2  V3  V4 
# 1 time1  a 144135 42435 345425 2342423 
# 2 time1  b 263766 35553 353453 3534553 
# 3 time1  c 355345 52454 525252 2423465 
# 4 time1  d 245466 45645 355345 6454556 
# 5 time1  f 355662 26397 353577 3558676 
# 6 time2  a 224234 23423 324234 4242324 
# 7 time2  c 312323 13123 312312 1312321 
# 8 time2  d 246456 63564 646544 4456456 
# 9 time2  f 244424 53556 546456 4645645 

數據:

text <- "metastring: time1, a,b,c,d,f\n144135 42435 345425 2342423\n263766 35553 353453 3534553\n355345 52454 525252 2423465\n245466 45645 355345 6454556\n355662 26397 353577 3558676\nmetastring: time2, a,c,d,f\n224234 23423 324234 4242324\n312323 13123 312312 1312321\n246456 63564 646544 4456456\n244424 53556 546456 4645645"