fork(1) download
  1. # 若 test.txt 內容如下
  2. 1234567 12345678 12345678901234
  3. sdfas sdfd sadf asdfasdff
  4. asgsdfas df
  5. asdfsd fsgsd sdfasgsd
  6. asdfsd fsgsd sdfasgsd df
  7. sdfgasd fsf sa
  8. dfsdffdfa
  9.  
  10. # 其中有三個欄,最大長度分別是 8 9 14
  11. # 有斷一次和斷二次的情況
  12. # 最後有一個全空白的列會比較好
  13.  
  14. library(data.table)
  15. library(magrittr)
  16.  
  17. d <-
  18. read.fwf(
  19. "test.txt",
  20. c(8, 9, 14), # 指定各欄最大寬度
  21. header = F,
  22. strip.white = T, # 清除多餘空白
  23. stringsAsFactors = F # 不要字串轉因子
  24. ) %>%
  25. as.data.table()
  26.  
  27. # 若 V1 和 V2 同時為空字串則視為斷列情況並把 V3 往上一列加到尾巴
  28. # 整個過程是由最末列做到最前列,方便處理超過一個斷列的情況
  29. for (i in rev(which(d[, "V1"] == "" & d[, "V2"] == ""))) {
  30. set(d, i-1L, "V3", paste0(d[i-1L, ]$`V3`, d[i, ]$`V3`))
  31. }
  32.  
  33. d[V1 != "" & V2 != ""] # 為所求
  34. # V1 V2 V3
  35. # 1: 1234567 12345678 12345678901234
  36. # 2: sdfas sdfd sadf asdfasdffasgsdfas df
  37. # 3: asdfsd fsgsd sdfasgsd
  38. # 4: asdfsd fsgsd sdfasgsd dfsdfgasd fsf sadfsdffdfa
Success #stdin #stdout #stderr 0.19s 183680KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected numeric constant in "1234567 12345678"
Execution halted