【问题标题】:How to sample by factor level, instead of row indices in R?如何按因子水平采样,而不是 R 中的行索引?
【发布时间】:2017-11-29 15:05:08
【问题描述】:

如何对数据框而不是行索引进行采样?

具体来说,我不确定如何更改 bs 函数中的 indices 参数以选择构成因子级别的多行,而不是仅选择单个行索引。对于上下文,我将函数 bsboot 包中的 boot 函数结合使用来引导置信区间。

函数bs 允许boot 函数使用indices 参数对数据帧进行采样。

bs <- function(data, indices) {
  d <- data[indices,] # allows boot function to select sample 
  shares <- aggregate(d$PASVINT3W, by=list(d$Prod), FUN = sum)
  shares <- shares[1:4 , ]
  names(shares) <- c("Prod", "sum.prob")
  shares <- shares$sum.prob/sum(shares$sum.prob)
  return(shares) 
} 

然后boot实际进行采样。

作为一个简化的示例,我有变量 type1,其中每两行分组,即 1、1、2、2、3、3。我想对这些分组进行抽样,而不是对单个行进行抽样。

     device geslacht leeftijd type1
1       mob        0       53     1     
2       tab        1       64     1     
3        pc        1       50     2     
4       tab        0       75     2     
5       mob        1       54     3     
6        pc        1       58     3     
7        pc        1       57     4     
8        pc        0       68     4     
9        pc        0       66     5     
10      mob        0       45     5     
11      tab        1       77     6     
12      mob        1       16     6   

【问题讨论】:

    标签: r dataframe sampling


    【解决方案1】:

    base R 选项将是

    lst <- split(seq_len(nrow(df1)), df1$type1)
    df1[unlist(lst[sample(names(lst))]),]
    

    或使用dplyr

    library(dplyr)
    df1 %>% 
       distinct(type1) %>%
       mutate(type1 = sample(type1)) %>%
       right_join(df1, .)
    

    【讨论】:

    • 非常感谢您的回答。我仍然有点不确定如何用bs 函数中的indices 参数合成基本的r 答案。我想我没有说清楚的一个重要部分是“引导”函数实际上处理了采样,但我不确定如何更改indices 参数以允许boot 对因子水平而不是个体进行采样行索引。
    • @RTrain3k unlist(lst[... 不会是索引
    • 好的,我明白你的意思了。如果后续函数boot 进行实际采样。我不需要排除[sample(names(lst))] 并且只包含`df1[unlist(lst),]?
    • 当我尝试上面提到的并运行boot 函数时,我收到错误`split.default(seq_len(nrow(data)), data$type1) 中的错误:组长度为0但数据长度> 0`
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多