【问题标题】:repeated whole vector sampling in r在 r 中重复整个向量采样
【发布时间】:2012-06-25 13:22:06
【问题描述】:

我有以下类型的数据

ntrt = paste ("EL", 1:4, sep= "")
repl = 3

我想从 ntrt 中采样,但是 3 次(rep = 3),输出如下:

nsam <- c(sample(ntrt),sample(ntrt), sample(ntrt)) 
repl <- rep (1:3, each = length (ntrt))
newd <- data.frame (nsam, repl)
newd 
 nsam repl
1   EL3    1
2   EL1    1
3   EL4    1
4   EL2    1

5   EL2    2
6   EL4    2
7   EL1    2
8   EL3    2

9   EL1    3
10  EL3    3
11  EL4    3
12  EL2    3

这是我的循环试验:

nsam <- rep (NULL, ntrt)
for (i in 1:rep){
         nsam[i] <- sample(ntrt)
         }

编辑:只是澄清

ntrt
[1] "EL1" "EL2" "EL3" "EL4"

> sample(ntrt,4)
[1] "EL4" "EL3" "EL2" "EL1" 

# is equal to:
sample(ntrt)

but what I need:
c(sample(ntrt), sample(ntrt), sample(ntrt))

[1] "EL4" "EL3" "EL1" "EL2" "EL1" "EL2" "EL3" "EL4" "EL3" "EL1" "EL2" "EL4"

which is equal to 
c(sample(ntrt,4), sample(ntrt,4), sample(ntrt,4))

因此过程是:

# for repl = 1
sample from ntrt  size = length(ntrt)

# repeat the same process again
# for repl = 2
sample from ntrt  size = length(ntrt)
# note: I only concerned with order of names within ntrt (randomization process)

# repeat the same process again
# for repl = 3
sample from ntrt  size = length(ntrt)

same process for n levels of repl

我遇到了错误,对不起一个简单的问题

【问题讨论】:

    标签: r loops random-sample


    【解决方案1】:

    看来您需要学习使用 R 中的帮助工具。sample 函数应该满足您的要求,即您只需提交第二个参数:

    ?sample      # to get the help page
    nsam <- sample(ntrt, 3)
    nsam
    #[1] "EL2" "EL1" "EL4"
    

    重复排列 3 次:

    replicate(3, sample(ntrt, length(ntrt)))
    

    【讨论】:

    • 请查看我的修改,了解我打算做什么,感谢您的建议
    • @ram replicate 也许?您的“澄清”对我来说并没有澄清太多。
    • @joran 我放了一个图来说明这个过程,如果有帮助,基本上想法是重复示例函数 sample(ntrt,4) number of repl
    【解决方案2】:

    尝试使用lapply

    set.seed(1) # Just so you can compare -- remove for your actual purposes
    ntrt = paste ("EL", 1:4, sep= "")
    repl <- rep (1:3, each = length (ntrt))
    nsam = unlist(lapply(1:3, FUN=function(i) sample(ntrt)))
    newd <- data.frame (nsam, repl)
    # > newd
    # nsam repl
    # 1   EL2    1
    # 2   EL4    1
    # 3   EL3    1
    # 4   EL1    1
    # 5   EL1    2
    # 6   EL3    2
    # 7   EL2    2
    # 8   EL4    2
    # 9   EL3    3
    # 10  EL1    3
    # 11  EL4    3
    # 12  EL2    3
    

    更新

    我注意到@joran 已经在评论中推荐了replicate。这是复制方法:

    data.frame(nsam = as.vector(replicate(3, sample(ntrt))), repl)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多