【问题标题】:Subset data frame in batches of 100 rows以 100 行为单位的子集数据框
【发布时间】:2016-06-15 21:08:34
【问题描述】:

我想按 100 行为一组对大型数据框进行子集化,以输入函数。

一个简化的例子:这是我的 1000 行的“大”数据框。

df<-data.frame(c(sample(2:100,1000,replace=TRUE)),c(sample(2:100,1000,replace=TRUE)))

我需要将 df[,1] 中的每组 100 行输入到这个虚拟函数中:

dummy<-function(x){
return(c("There are ",x," dummies in this room"))
}

我需要以 100 个为一组执行此操作,因为虚拟函数一次只能处理 100 个值。

这会将整个 df[,1] 输入到函数中:

lapply(df[,1],dummy)

但是,我需要这样的东西:

lapply(df[1:100,1],dummy)
lapply(df[101:200,1]dummy)
. . . etc

我如何以简洁的方式做到这一点,最好使用 base r?

【问题讨论】:

    标签: r recursion subset lapply


    【解决方案1】:

    如果您的数据集中没有因子变量,请使用split on 或者您不想走cut 的向量路径,这样的简短程序可能就足够了:

    df<-data.frame(c(sample(2:100,1000,replace=TRUE)),c(sample(2:100,1000,replace=TRUE)))
    sample<-list()
    div<-seq(100,nrow(df),100)
    for(i in 1:length(div))
    {
        sample[[i]]<-df[(100*(i-1)):div[i],]
    }
    

    【讨论】:

    • Hanjo,为什么 sample[2] 产生第 1 200 行而不是第 101-200 行?
    • @CatherineSmith,更正了代码。此外,当引用列表项时,约定是使用双括号[[。所以调用你的第二个样本数据集是sample[[2]]。希望对你有所帮助
    • 代码采样 1:100,然后在下一个示例中复制第 100 行。此外,由于数据框可能具有 nrow%%100!=0,因此此修改后的代码对我有用,并且仅从 df 提供我需要的列:sample&lt;-list() div&lt;-seq(100,(nrow(df)+99),100) for(i in 1:length(div)) { sample[[i]]&lt;-df[(100*(i-1)+1):div[i],1] } sample&lt;-lapply(sample, function(x) x[!is.na(x)])
    【解决方案2】:

    正如@A Webb 所建议的,使用split 应该会有所帮助。

    df<-data.frame(c(sample(2:100,1000,replace=TRUE)),
                   c(sample(2:100,1000,replace=TRUE)))
    
    # For sequential grouping
    groups<-10 
    split(df, factor(sort(rank(row.names(df))%%groups)))
    
    # For Random sampling of 100
    split(df, sample(1:groups, nrow(df), replace=T))
    
    sapply(groups_split, yourfunc)
    

    可能存在更有效的方法,希望看到新的答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-16
      • 2017-12-25
      • 1970-01-01
      • 2023-02-23
      • 2021-07-22
      • 2020-02-10
      • 1970-01-01
      • 2022-10-20
      相关资源
      最近更新 更多