次のようなデータフレーム (df2) があります。
locus transect fq d
Locus_1 A 0.000 20
Locus_1 A 0.000 35
Locus_1 A 0.000 50
Locus_2 A 0.200 20
Locus_2 A 0.083 35
Locus_2 A 0.125 50
Locus_3 A 0.134 20
Locus_3 A 0.208 35
Locus_3 A 0.218 50
Locus_4 A 0.000 20
Locus_4 A 0.000 35
Locus_4 A 0.000 50
Locus_5 A 0.100 20
Locus_5 A 0.000 35
Locus_5 A 0.038 50 ...
基本的に、各遺伝子座は、中心からの距離が異なるトランセクトに沿って 3 回サンプリングされます。何千もの遺伝子座があります。このデータセットから、頻度と距離の相関を計算します。
次の手順は次のとおりです。
- 各遺伝子座の位置をランダム化し (つまり、最初の 3 行、2 番目の 3 行のグループなど)、新しい相関を計算します。基本的に、各遺伝子座間で d 値 (20-35-50) をシャッフルしたいと考えています。イオン
- これを1000回
- 各複製の結果を保存します
Plyr
主にとを使おうとしていますdplyr
。
これは私が思いついたコードです:
df3 <- group_by(df2, transect, locus) #setting up groups to which apply functions
data <- replicate(1000, {
test <- sample_n(df3, 3, replace=F) #shuffle by group
Rho <- ddply(test, .(transect, locus), summarise, corr= cor(fq, d, method = "spearman")) #calculate correlation
Rho[is.na(Rho)] <- 0 #replacing missing values with zero
Rho_mean_bylocus <- ddply(Rho, .(locus), summarise, mean=mean(corr)) #average correlation over transect
}, simplify = TRUE)
結果は次のようになります。
[,1] [,2] [,3] [,4]
locus factor,978 factor,978 factor,978 factor,978
mean Numeric,978 Numeric,978 Numeric,978 Numeric,978
[,5] [,6] [,7] [,8]
locus factor,978 factor,978 factor,978 factor,978
mean Numeric,978 Numeric,978 Numeric,978 Numeric,978
[,9] [,10]
locus factor,978 factor,978
mean Numeric,978 Numeric,978
(私は978個の遺伝子座を持っています)。
replicate()
関数に埋め込んでみました
rand.rho <- function(x) { #I have tried also without using a function, but still does not work
data <- replicate(1000, {
test <- sample_n(df3, 3, replace=F) #shuffle
Rho <- ddply(test, .(transect, locus), summarise, corr= cor(fq, d, method = "spearman")) #calculate correlation
Rho[is.na(Rho)] <- 0 #replacing missing values with zero
Rho_mean_bylocus <- ddply(Rho, .(locus), summarise, mean=mean(corr)) #average correlation over transect
}, simplify = TRUE)
df4 <- rand.rho(df3)
しかし、私はエラーが発生します:
Error in list_to_dataframe(res, attr(.data, "split_labels"), .id, id_as_factor) :
Results must be all atomic, or all data frames
In addition: There were 50 or more warnings (use warnings() to see the first 50)
私は途方に暮れています。
ここですでに他の回答を探し、提案を実装しようとしましたが、まだ機能していません。
何かアドバイス?