首页 文章

从数据帧中的组重复采样并应用函数

提问于
浏览
1

这是两个问题的组合(Repeat the re-sampling function for 1000 times ? Using lapply?How do you sample groups in a data.table with a caveat) .

目标是在data.table中对组进行采样,但是重复此过程“n”次并拉出每个行值的平均值 . 例如:

#generate the data
DT = data.table(a=c(1,1,1,1:15,1,1), b=sample(1:1000,20))

#sample the data as done in the second linked question
DT[,.SD[sample(.N,min(.N,3))],by = a]
     a   b
 1:  1 288
 2:  1 881
 3:  1 409
 4:  2 937
 5:  3  46
 6:  4 525
 7:  5 887
 8:  6 548
 9:  7 453
10:  8 948
11:  9 449
12: 10 670
13: 11 566
14: 12 102
15: 13 993
16: 14 243
17: 15  42

现在,我尝试使用第一个链接问题中给出的答案:

x <- replicate(100,{DT[,.SD[sample(.N,min(.N,3))],by = a]})

每次重复都会返回一个列表“x” . 我能想到访问重复的唯一方法是:

# repetition 1 col-a values
x[[1]]
# repetition 1 col-b values
x[[2]]
# repetition 2 col-a values
x[[3]]
# repetition 2 col-b values
x[[4]]

所以为了达到每一行的平均值,我必须找到 x[[j]] 的平均值,其中 j 来自 seq(2,200,2) ,其中 200 是复制数* 2 .

有更简单的方法吗?我试过以这种方式使用这个解决方案(https://stats.stackexchange.com/questions/8225/how-to-summarize-data-by-group-in-r):

y <- DT[,.SD[sample(.N,min(.N,3))],by = a]
y[,list(mean=mean(b)),by=a]
     a mean
 1:  1  550
 2:  2  849
 3:  3  603
 4:  4   77
 5:  5  973
 6:  6  746
 7:  7  919
 8:  8  655
 9:  9  883
10: 10  823
11: 11  533
12: 12  483
13: 13   53
14: 14  827
15: 15  413

但我还没有能够通过复制过程来做到这一点 . 任何帮助都会很棒!

1 回答

  • 1

    这样的事情?

    根据您的评论,您希望每个复制按组分配,因此在此示例中,15 * 100表示 . 这有两种方法可以做到这一点 .

    library(data.table)
    set.seed(1) # for reproducibility
    DT = data.table(a=c(1,1,1,1:15,1,1), b=sample(1:1000,20))
    x <- replicate(100,{DT[,.SD[sample(.N,min(.N,3))],by = a]})
    
    indx <- seq(1,length(x),2)
    result.1 <- mapply(function(a,b)aggregate(b,list(a),mean)$x,x[indx],x[indx+1])
    str(result.1)
    #  num [1:15, 1:100] 569 201 894 940 657 625 62 204 175 679 ...
    result.2 <- sapply(x[indx+1],function(b)aggregate(b,x[1],mean)$x)
    identical(result.1,result.2)
    # [1] TRUE
    

    两种方法都产生15×100的平均值矩阵,其中组在行中并且复制在列中 . 第二种方法利用了事实 a 列对于所有重复都是相同的 .

相关问题