2

次のタイプのデータがあります

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

エラーが発生しています。単純な質問で申し訳ありません

4

2 に答える 2

4

使ってみてください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)
于 2012-06-23T17:15:23.380 に答える
1

R のヘルプ機能の使い方を学ぶ必要があるようです。sample関数は、2 番目の引数を送信するだけで、あなたが求めているように見えることを実行する必要があります。

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

順列を 3 回繰り返すには:

replicate(3, sample(ntrt, length(ntrt)))
于 2012-06-23T13:36:01.623 に答える