How to write to a file in tab delimited manner?
Asked Answered
R

1

8

So I have this data frame from a bed file called input.bed:

     V1       V2       V3  V4
 1 chr1 11323785 11617177 TF1
 2 chr1 12645605 13926923 TF2
 3 chr1 14750216 15119039 TF3
 4 chr1 18102157 19080189 TF1
 5 chr1 29491029 30934636 TF2
 6 chr1 33716472 35395979 TF4
 7 chr1 36712462 37685238 TF5
 8 chr1 37838094 38031209 TF3

It's a data frame I read from a .bed file (the .bed file is tab delimited). I want to take each row and output it to a different file. Say row1 I want it to be in input1.bed , row 2 in input2.bed

This has been my attempt:

 for(i in 1:nrow(input.bed))
  {
    file.create(paste("input",i,".bed",sep=""));

   }

 for(i in 1:nrow(input.bed))
 {
    write.table(unlist(input.bed[i,]),paste("input",i,".bed",sep=""),sep="\t");

}

For some reason the output of my files ,this is from input1.bed, is:

    "V1"    "chr1"
    "V2"    "11323785"
    "V3"    "11617177"
    "V4"    "TF1"

But I want the output to be tab delimited like this:

    chr1 11323785 11617177 TF1

What am I doing wrong?

Response answered 15/11, 2017 at 19:27 Comment(2)
don't use unlist(). and maybe add quote=FALSE and row.names=FALSE to your write.table()Piceous
Also no need to create the files first - write.table will create themPentomic
G
7

You can use just one for loop in the following manner (q is your data frame)

for(i in 1:nrow(q)){
  write.table(x = q[i,], 
              file = paste('input',i,'.bed',sep=''), 
              row.names = F, 
              col.names = F, 
              quote = F, 
              sep = '\t')
}

Basically your approach was correct, you just need to inform the function that you do not want all default behaviors (i.e. col/rownames, quotes).

Glaucescent answered 15/11, 2017 at 19:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.