r - R - 按行位置拆分数据集并保存在不同的文件中
问题描述
我有一个巨大的数据集,其中合并了几个迷你数据集。我想将它们拆分为不同的数据帧并保存它们。迷你数据集由给定行上的变量名称(始终包括字符串“-gram”)标识。
我一直在尝试构建一个for
循环,但没有运气。
grams <- read.delim("grams.tsv", header=FALSE) #read dataset
index <- which(grepl("-gram", grams$V1), arr.ind=TRUE) # identify the row positions where each mini dataset starts
index[10] <- nrow(grams) # add the total number of rows as last variable of the vector
start <- c() # initialize vector
end <- c() # initialize vector
for (i in 1:length(index)-1) for ( k in 2:length(index)) {
start[i] <- index[i] # add value to the vector start
if (k != 10) { end[k-1] <- index[k]-1 } else { end[k-1] <- index[k] } # add value to the vector end
gram <- grams[start[i]:end[i],] #subset the dataset grams so that the split mini dataset has start and end that correspond to the index in the vector
write.csv(gram, file=paste0("grams_", i, ".csv"), row.names=FALSE) # save dataset
}
当我尝试对数据集进行子集化时出现错误:
start[i]:end[i] 中的错误:长度为 0 的参数
...我不明白为什么!谁能帮我?
谢谢!
解决方案
您可以cumsum
:split
dat <- data.frame(V1 = c("foo", "bar", "quux-gram", "bar-gram", "something", "nothing"),
V2 = 1:6, stringsAsFactors = FALSE)
dat
# V1 V2
# 1 foo 1
# 2 bar 2
# 3 quux-gram 3
# 4 bar-gram 4
# 5 something 5
# 6 nothing 6
grepl("-gram$", dat$V1)
# [1] FALSE FALSE TRUE TRUE FALSE FALSE
cumsum(grepl("-gram$", dat$V1))
# [1] 0 0 1 2 2 2
spl_dat <- split(dat, cumsum(grepl("-gram$", dat$V1)))
spl_dat
# $`0`
# V1 V2
# 1 foo 1
# 2 bar 2
# $`1`
# V1 V2
# 3 quux-gram 3
# $`2`
# V1 V2
# 4 bar-gram 4
# 5 something 5
# 6 nothing 6
有了它,您可以将它们写入文件:
ign <- Map(write.csv, spl_dat, sprintf("gram-%03d.csv", seq_along(spl_dat)),
list(row.names=FALSE))
推荐阅读
- c# - 源代码更改时 WPF 自动构建和重新加载
- python - 执行 Sql 脚本返回“无”
- python - 为什么对象在 for 循环中加速?
- linux - 带有单独结果的 bash 简单搜索脚本
- r - 我想提高我的 hts 时间序列预测的准确性(MAPE)
- php - 递归循环遍历多维数组并对每个键值做一些事情
- jenkins-pipeline - 来自 AWS ECR 的 Jenkins 管道 Docker 代理
- c# - c# dllimport 试图加载格式不正确的程序
- c++ - set_union() 不适用于一组字符串
- django - 如何在 django 自定义保存方法中访问数据库对象?