首页 > 解决方案 > 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 的参数

...我不明白为什么!谁能帮我?

谢谢!

标签: rdataframefor-loopsplit

解决方案


您可以cumsumsplit

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

推荐阅读