簡體   English   中英

讀取以豎線和逗號分隔的文件:| column1 |,| column2 |

[英]Read files that are pipe AND comma delimited: |column1|,|column2|

我的文件看起來像這樣:

|2000|,|23456745|,|23567897tyhgy6|,|SHARP, RODNEY H III|
|2000|,|12345678|,|34567tgh788877|,|WOOLARD, EDGAR S JR|

基本上,這些列用逗號分隔並用管道包裹。

我如何使用R讀取類似的內容?

我努力了

read.table("file.txt", sep="|")

但這行不通,因為其他所有列都只包含一個逗號。 我嘗試使用“ |,|” 作為分隔符,但顯然不允許這樣做。 使用“,”根本不起作用,因為名稱隨后被分割了。

有任何簡單的方法嗎?

您可以嘗試將其替換為其他分隔符:

plouf <-   readChar("file.txt", file.info("file.txt")$size)
plouf <- gsub("\\|,\\|",";",plouf) # replace the separator
plouf <- gsub("\\|","",plouf) # remove the end pipes
read.table(plouf,sep=";") # read with the semi colon sep

一個測試:

plouf <- "|2000|,|23456745|,|23567897tyhgy6|,|SHARP, RODNEY H III|
          |2000|,|12345678|,|34567tgh788877|,|WOOLARD, EDGAR S JR|"

plouf <- gsub("\\|,\\|",";",plouf)
plouf <- gsub("\\|","",plouf)
read.table(text = plouf,sep=";")

    V1       V2             V3                  V4
1 2000 23456745 23567897tyhgy6 SHARP, RODNEY H III
2 2000 12345678 34567tgh788877 WOOLARD, EDGAR S JR

read.table("./temp.csv", sep=",", quote = "|")可以解決問題...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM