【发布时间】:2020-09-04 11:25:53
【问题描述】:
我有一个巨大的数据集,其中合并了几个迷你数据集。我想将它们拆分为不同的数据帧并保存它们。迷你数据集由给定行上的变量名称(始终包含字符串“-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 的参数
...我不明白为什么!谁能帮帮我?
谢谢!
【问题讨论】:
标签: r dataframe for-loop split