Group Data Every 3 Lines and Join Lines Up in Each Group
【Question】
I would like to convert a file:
hello
world
123
bye
world
456
byee
world
456678
To a CSV file like this:
hello,world,123
bye,world,456
byee,world,456678
A solution offered:
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"
))
【Answer】
A natural way is to delete the blank lines, group data every 3 lines, and join lines up in every group with the comma. Here I achieve it with SPL (Structured Process Language):
A |
|
1 |
=file("d:\\source.txt").read@n().select(~!="") |
2 |
=A1.group((#-1)\3).(~.concat@c()) |
3 |
=file("d:\\result.csv").write(A2) |
A1: Read in content from source. txt and get non-blank lines.
A2: Group the selected data every 3 lines and concatenate lines in each group into a comma-separated string.
A3: Write A2’s result to result.csv.
SPL Official Website 👉 https://www.scudata.com
SPL Feedback and Help 👉 https://www.reddit.com/r/esProc_SPL
SPL Learning Material 👉 https://c.scudata.com
SPL Source Code and Package 👉 https://github.com/SPLWare/esProc
Discord 👉 https://discord.gg/cFTcUNs7
Youtube 👉 https://www.youtube.com/@esProc_SPL