【问题标题】:How can I split a CSV file into small chunks? [duplicate]如何将 CSV 文件拆分成小块? [复制]
【发布时间】:2016-03-11 13:27:24
【问题描述】:

我想弄清楚如何将 CSV 文件拆分成小块。我想按任意数量或行拆分。也许是 20、1,000 或其他。

setwd("C:/Users/my_path/test_folder/") 
mydata = read.csv("NHLData.csv") 


split(mydata, ceiling(seq_along(mydata)/20)) 

错误:警告消息:在 split.default(x = seq_len(nrow(x)), f = f, drop = drop, ...) 中:数据长度不是拆分变量的倍数

我也试过这个。

split(mydata, ceiling(seq_along(mydata)/(length(mydata)/20)))

同样的错误:警告消息:在 split.default(x = seq_len(nrow(x)), f = f, drop = drop, ...) 中:数据长度不是拆分变量的倍数

我在 Google 上搜索了这些想法。我真的没有找到其他有用的东西。这一定很简单吧。

【问题讨论】:

标签: r


【解决方案1】:

利用 'sample' 功能,会有所帮助。

setwd("C:/Users/my_path/test_folder/") 
mydata = read.csv("NHLData.csv") 

# If you want 5 different chunks with same number of lines, lets say 30.
Chunks = split(mydata,sample(rep(1:5,30)))  ## 5 Chunks of 30 lines each

# If you want 20 samples, put any range of 20 values within the range of number of rows
First_chunk <- sample(mydata[1:20,])  ## this would contain first 20 rows

# Or you can print any number of rows within the range
Second_chunk <- sample(mydata[100:70,] ## this would contain last 30 rows in reverse order if your data had 100 rows.

# If you want to write these chunks out in a csv file:
write.csv(First_chunk,file="First_chunk.csv",quote=F,row.names=F,col.names=T)
write.csv(Second_chunk,file="Second_chunk.csv",quote=F,row.names=F,col.names=T)

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2019-03-14
    • 1970-01-01
    • 2018-09-30
    • 2013-06-01
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    • 2020-05-06
    • 2011-08-05
    相关资源
    最近更新 更多