tubby
tubby

Reputation: 2144

convert text file separated by new line to csv file

I would like to convert a file like follows

hello
world
123

bye
world
456

byee
world
456678

to a csv file like

hello,world,123
bye,world,456
byee,world,456678

Is is possible to do this without iterating through the entire file and seeing for new line?

Upvotes: 3

Views: 954

Answers (3)

G. Grothendieck
G. Grothendieck

Reputation: 269654

Scan it in, shape it into a 3 column matrix by row and write it out. (Replace the first argument of scan and second argument of write.table with the input and output file names.)

m <- matrix(scan(textConnection(Lines), what = ""), ncol = 3, byrow = TRUE)
write.table(m, stdout(), sep = ",", row.names = FALSE, col.names = FALSE, quote = FALSE)

giving:

hello,world,123
bye,world,456
byee,world,456678

Note

We used this as the input

Lines <- "hello
world
123

bye
world
456

byee
world
456678"

Upvotes: 1

Brandon Bertelsen
Brandon Bertelsen

Reputation: 44648

dat <- readLines( # con = 'path/to/your/file'
   con = textConnection('hello
world
123

bye
world
456

byee
world
456678')

write.csv(
  t(matrix(
    dat[-seq(4,length(dat),4)], # Drop the spacer
    length(dat)/3,3), # Estimate columns
  file = "path/to/your.csv" 
  ))

Upvotes: 1

IRTFM
IRTFM

Reputation: 263352

Use the multi.line capacity of scan and then write.table with appropriate parameters:

txt <- "hello
world
123

bye
world
456

byee
world
456678"
temp <- data.frame( scan(text=txt, 
                    what= list( word="", dest="", num=numeric(), "NULL"), 
                    multi.line=TRUE))
 write.table(temp, sep=",", file="", quote=FALSE,col.names=FALSE)
#-------------
1,hello,world,123,
2,bye,world,456,
3,byee,world,456678,

Obviously you would use a legal file name if you wanted this sent to disk.

Upvotes: 2

Related Questions