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?
A CSV (Comma Separated Values) or Tab-delimited Text (or Tab Separated Values) file is a text file in which one can identify rows and columns. Rows are represented by the lines in the file and the columns are created by separating the values on each line by a specific character, like a comma or a tab.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With