每三行分组后合并起来

【问题】

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

别人解法

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

【回答】

       直观的解法是:删掉空行,每3行分一组,各组用逗号拼成一行。如无特殊要求,可用SPL实现:

A
1=file("d:\\source.txt").read@n().select(~!="")
2=A1.group((#-1)\3).(~.concat@c())
3=file("d:\\result.csv").write(A2)

A1:读取文本文件source.txt中的内容,并选出非空行。

A2:每3个一组,每组拼成逗号分隔的字符串。

A3:将A2结果写入文件result.csv。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值