Search code examples
rdplyrdata.tablefixed-width

How to write dataframe to file so that regardless of length of column values, the values are adjacent without spaces


I have a dataframe that looks like this:

V1 V2 V3
1 06  1
06 1  1
0 08  1
08 0  1
0 06  1
06 0  1

I want to write to text file in fixed-width format so that it looks like this:

1061
0611
0081
0801
0061
0601

At the moment, I'm using write.fwf from gdata:

write.fwf(colnames=FALSE, x=df,file='file.txt', sep="")

But that produces output like this:

1 061
061 1
0 081
080 1
0 061
060 1

.. the spaces are preserved.

I'm thinking I convert each row to a single value with rowwise() mutate(), then output, or convert to single rows using read.table -- though that seems to eat the leading zeros, which I need

But I wanted to see what the most intuitive way to accomplish this task is.


Solution

  • You can convert it to a vector in R, as suggested in comments, or use:

    write.table(df, "file.txt", sep = "", quote = FALSE, col.names = FALSE)