按分隔符读取表格,然后按R中的固定宽度读取

时间:2013-07-31 17:08:22

标签: r io data-manipulation

我有一个制表符分隔的文件,如下所示:

RS1->2001 HAPLO1 AAACAAGGAGGAGAAGGAAA ...
RS1->2001 HAPLO2 CAACAAAGAGGAGAAGGAAA ...
RS1->2002 HAPLO1 AAAAAAGGAGGAAAAGGAAA ...
RS1->20020 HAPLO2 CAACAAGGAGGAAGCAGAGC ...
RS1->20021 HAPLO2 CAACAAGGAGGAAGCAGAGC ...

在R中我们可以轻松阅读这三列,我的问题是我需要按字符分隔第3列。最终结果应该是这样的:

RS1->2001 HAPLO1 A A A C  ...
RS1->2001 HAPLO2 C A A C  ...
RS1->2002 HAPLO1 A A A A  ...
RS1->20020 HAPLO2 C A A C  ...
RS1->20021 HAPLO2 C A A C  ...

我可以先读取3列,然后将第3列的每个条目分成字符,但这很烦人,我非常希望从一开始就把它弄好。

如果前两列没有出现,我可以用

实现目标
read.fwf('test.csv', widths=rep(1, 300))

我在想是否可以使用制表符分隔符读取前2列,然后按固定宽度读取第3列。

3 个答案:

答案 0 :(得分:1)

正如@Ananda在评论中提到的那样,strsplit如果被要求分开""将分开每封信。

fContents <- read.csv("/path/to/file.csv")

 # This will chop it up for you.
 strsplit(fContents[, 3], "")

要合并它,请使用cbind

cbind(fContents[, -3],
       do.call(rbind, strsplit(fContents[, 3], ""))
      )

# or if you'd like to keep the columns ordered (and there are more than 3):
cbind(fContents[, 1:2], 
      do.call(rbind, strsplit(fContents[, 3], "")),
      fContents[, 4:ncol(fContents)]
)

答案 1 :(得分:1)

我想到的两个主要选项是strsplit(如评论和@ Ricardo的回答中提到的)和read.fwfread.fwf不会直接处理您的数据,但如果您使用textConnection()函数,它可以处理已读入的数据列。

这是一个基本的例子:

## Create a tab-separated file named "test.txt" in your working directory
cat("2001\tHAPLO1\tAAACAAGGAGGAGAAGGAAA\n",
    "2001\tHAPLO2\tCAACAAAGAGGAGAAGGAAA\n",
    "2002\tHAPLO1\tAAAAAAGGAGGAAAAGGAAA\n",
    "20020\tHAPLO2\tCAACAAGGAGGAAGCAGAGC\n",
    "20021\tHAPLO2\tCAACAAGGAGGAAGCAGAGC\n", 
    file = "test.txt")

## Read it in with `read.delim`
mydata <- read.delim("test.txt", header = FALSE, stringsAsFactors = FALSE)

## Use `read.fwf` on the third column
## Replace "widths" with whatever the maximum width is for that column
## If max width is not known, you can use something like
##    `widths = rep(1, max(nchar(mydata$V3)))`
cbind(mydata[-3], 
      read.fwf(file = textConnection(mydata$V3), widths = rep(1, 20)))
#      V1     V2 V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20
# 1  2001 HAPLO1  A  A  A  C  A  A  G  G  A   G   G   A   G   A   A   G   G   A   A   A
# 2  2001 HAPLO2  C  A  A  C  A  A  A  G  A   G   G   A   G   A   A   G   G   A   A   A
# 3  2002 HAPLO1  A  A  A  A  A  A  G  G  A   G   G   A   A   A   A   G   G   A   A   A
# 4 20020 HAPLO2  C  A  A  C  A  A  G  G  A   G   G   A   A   G   C   A   G   A   G   C
# 5 20021 HAPLO2  C  A  A  C  A  A  G  G  A   G   G   A   A   G   C   A   G   A   G   C

注意:如果您未使用stringsAsFactors = FALSE,则必须将file参数更改为:

file = textConnection(as.character(mydata$V3))

答案 2 :(得分:0)

import csv
file_read = csv.reader(open('/path/to/file.csv','r'),delimiter='\t')
file_write = csv.writer(open('/path/to/newfile.csv','w'),delimiter='\t')
for i in file_read:
    first=i[0]
    second=i[1]
    third = i[3]
    splitchar = [k for k in third]
    outputdata = [first,second,splitchar]
    file_write.writerow(outputdata)