简体   繁体   中英

Write.table not separating by comma

Why doesn't this write out the csv as (4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4) (when viewed in Notepad)

results <- data.frame(Answer= rep(4,16))
write.table(results$Answer, file = "paul.csv", row.names=FALSE, col.names=FALSE, sep=",")

It's as if its ignored the Sep argument..? Paul

You should not define variable as one column if you want sep to work because sep = ... works with columns. This is one way you can do it:

results <- data.frame(t(rep(4,16)))
write.table(results, file = "paul.csv", row.names=FALSE, col.names=FALSE, sep=",")

There are two simple possibilities.
One, use argument eol = "," like I have said in my comment above. The problem with this method is that it will include an extra "," at the end of the line, since write.table always includes an ending newline.

write.table(results$Answer, file = "paul.csv", row.names = FALSE, col.names = FALSE, eol = ",")

The other method is to use cat .

cat(results$Answer, file = "paul.csv", sep = ",")

I believe this is the one you want.

You have specified a vertical vector. When a vertical vector is being written, each vector element is written into an own line:

> results <- data.frame(Answer= rep(4,16))
> dim(results)
[1] 16  1
> results
   Answer
1       4
2       4
3       4
4       4
5       4
6       4
7       4
8       4
9       4
10      4
11      4
12      4
13      4
14      4
15      4
16      4

If you want to write the vector in a single line, you may transpose a vertical vector into a horizontal vector using function t( ) :

> results <- t(data.frame(Answer= rep(4,16)))
> dim(results)
[1]  1 16
> results
       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16]
Answer    4    4    4    4    4    4    4    4    4     4     4     4     4     4     4     4

Then writing the data into a file:

> results <- t(data.frame(Answer= rep(4,16)))
> write.table(results$Answer, file = "paul.csv", row.names=FALSE, col.names=FALSE, sep=",")

will yield the following contents:

4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM