Convert newline delimited text file to csv file

I would like to convert the file as shown below

hello
world
123

bye
world
456

byee
world
456678

      

to a csv file like

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

      

Is it possible to do this without repeating the entire file and looking at a new line?

+3


source to share


3 answers


Use the capacity multi.line scan

and then write.table with the appropriate options:

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 the legal file name if you wanted this sent to disk.

+2


source


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" 
  ))

      



+1


source


Scan it, arrange it into a 3-column matrix and write it down. (Replace the first argument scan

and second argument write.table

with the names of the input and output files.)

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 an input

Lines <- "hello
world
123

bye
world
456

byee
world
456678"

      

+1


source







All Articles