fork download
  1. library(magrittr) # 有pipe用,沒其它作用
  2.  
  3. # 還原原始資料文字檔為dt.txt
  4. txt <- "V1
  5. LAYER: 34 ;
  6. DATATYPE: 0 ;
  7. 0;0
  8. 10;0
  9. 10;0.9
  10. 0;0.9
  11. 0;0
  12. LAYER: 34 ;
  13. DATATYPE: 0 ;
  14. 0;9.1
  15. 10;9.1
  16. 10;10
  17. 0;10
  18. 0;9.1
  19. LAYER: 44 ;
  20. DATATYPE: 10 ;
  21. 9.52;1.3
  22. 9.8;1.3
  23. 9.8;9.1
  24. 9.52;9.1
  25. 9.52;1.3
  26. "
  27. cat(txt, file = "dt.txt")
  28.  
  29. # 讀文字檔並做初步清理
  30. con <- file("dt.txt", "r")
  31. txt <- readLines(con)[-1] %>% gsub("( +;$)|( +)", "", .)
  32. close(con)
  33.  
  34. # 捉到LAYER列與DATATYPE列及其資料
  35. r.layer <- grep("^LAYER:[[:digit:]]+$", txt)
  36. c.layer <- txt[r.layer] %>% gsub("LAYER:", "", .) %>% as.integer
  37. r.datatype <- grep("^DATATYPE:[[:digit:]]+$", txt)
  38. c.datatype <- txt[r.datatype] %>% gsub("DATATYPE:", "", .) %>% as.integer
  39.  
  40. # 捉出每一群有幾項
  41. n <- diff(c(r.layer, length(txt)+1)) - 2
  42.  
  43. data.frame(
  44. V1 = txt[-c(r.layer, r.datatype)],
  45. group = rep.int(1:length(n), n),
  46. `L;D` = paste0(c.layer, ";", c.datatype) %>% rep(., n)
  47. )
  48.  
Success #stdin #stdout 0.27s 39484KB
stdin
Standard input is empty
stdout
         V1 group   L.D
1       0;0     1  34;0
2      10;0     1  34;0
3    10;0.9     1  34;0
4     0;0.9     1  34;0
5       0;0     1  34;0
6     0;9.1     2  34;0
7    10;9.1     2  34;0
8     10;10     2  34;0
9      0;10     2  34;0
10    0;9.1     2  34;0
11 9.52;1.3     3 44;10
12  9.8;1.3     3 44;10
13  9.8;9.1     3 44;10
14 9.52;9.1     3 44;10
15 9.52;1.3     3 44;10