繁体   English   中英

将TXT文件分成每X行几个文件(使用R)

[英]Split TXT file into several files each X rows(using R)

我有一个包含1000万行的txt文件(“ JT.txt”)。 我想以最简单的方式将其拆分为同一目录中的每200.000行的几个文件,并使用模式“ JT_1.txt”,“ JT_2.txt”等调用文件名。如何使用R做到这一点?

在这里分享我的逻辑:

mtcars$rows <- 1:nrow(mtcars)  # create a index
mtcars$rows <- cumsum(mtcars$rows %% 2)  # this creates blocks of 2 rows

# now we just split it : I think , this should work. add write.table() inside lapply()
lapply(split(mtcars, mtcars$rows), function(x) paste0("mytext", unique(x[["rows"]]), ".csv"))
#create a sequence of indices for splitting the data by increment of N
N = 6;

splitIndices = seq(1,nrow(mtcars),N)

#for each index, split dataset and export
lapply(splitIndices,function(x)  { 
    minIndex = x; 
    maxIndex = min(x+N-1,nrow(mtcars)); 
    DF = mtcars[minIndex:maxIndex,] 
    write.table(DF,paste0("JT_",1+as.integer(x/N),"_.txt"))
    } )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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