【问题标题】:R - split dataset by row position and save in different filesR - 按行位置拆分数据集并保存在不同的文件中
【发布时间】: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


    【解决方案1】:

    group_splitendsWith 的选项

    library(dplyr)
    library(stringr)
    dat %>%
          group_split(grp = cumsum(endsWith(V1, '-gram')), keep = FALSE)
    

    【讨论】:

      【解决方案2】:

      你可以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))
      

      【讨论】:

      • 很好,谢谢!只是出于好奇——这怎么能在for 循环中完成?为什么我的循环不起作用?
      • for (i in seq_along(spl_dat)) write.csv(spl_dat[[i]], paste0("gram-", i, ".csv"), row.names=FALSE)?
      • 我的意思是在我的循环中。我仍然不明白它有什么问题。
      • 也许 1:5 - 1 以 0 开头,但没有一个数组可以与 [0] 一起使用。你的意思是1:(length(index)-1)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-15
      • 2020-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多