is.na()
R の for ループでの動作に混乱しています。
一連の数字を作成し、マトリックスに何かを行い、一連の数字に基づいて結果のマトリックスを要約し、要約に基づいて一連の数字を変更して繰り返す関数を作成しようとしています。まだ問題が発生していると思うので、関数の単純なバージョンを作成しました。
library(plyr)
test <- function(desired.iterations, max.iterations)
{
rich.seq <- 4:34 ##make a sequence of numbers
details.table <- matrix(nrow=length(rich.seq), ncol=1, dimnames=list(rich.seq))
##generate a table where the row names are those numbers
print(details.table) ##that's what it looks like
temp.results <- matrix(nrow=10, ncol=2, dimnames=list(1:10))
##generate some sample data to summarize and fill into details.table
temp.results[,1] <- rep(5:6, 5)
temp.results[,2] <- rnorm(10)
print(temp.results) ##that's what it looks like
details.table[,1][row.names(details.table) %in% count(temp.results[,1])$x] <-
count(temp.results[,1])$freq
##summarize, subset to the appropriate rows in details.table, and fill in the summary
print(details.table)
for (i in 1:max.iterations)
{
rich.seq <- rich.seq[details.table < desired.iterations | is.na(details.table)]
## the idea would be to keep cutting this sequence of numbers down with
## successive iterations until the desired number of iterations per row in
## details.table was reached. in other words, in the real code i'd do
## something to details.table in the next line
print(rich.seq)
}
}
##call the function
test(desired.iterations=4, max.iterations=2)
for ループの最初の実行では、rich.seq は予想どおりのように見えます。5 と 6 は、どちらも 4 回以上の反復で終了したため、シーケンスに含まれていません。しかし、2回目の実行で、予期しないものを吐き出します。
アップデートご協力ありがとうございます。また、お詫び申し上げます。元の投稿を読み直した後、それは明確ではないだけでなく、 count が plyr パッケージの一部であることに気付きませんでした。もっとうまく説明しようと思います。
私が現在取り組んでいるのは、マトリックスを取り、それを(さまざまな方法のいずれかで)ランダム化し、その上でいくつかの統計を計算する関数です。これらの統計は、temp.results テーブルに一時的に保存されます。ここで、temp.results[,1] は各列のゼロ以外の要素の合計であり、temp.results[,2] はその別の要約統計です。桁。これらの結果を csv ファイルに保存します (そして、後続の反復で同じファイルに追加します)。これは、その結果をループして rbinding すると多くのメモリが占有されるためです。
問題は、特定の列の合計 (temp.results[,1]) が非常にまれにサンプリングされることです。それらを十分にサンプリングするには、何回もの反復が必要であり、結果の .csv ファイルは数百ギガバイトにまで拡大します。
私がやりたいことは、各列の合計が実際にサンプリングされた回数を追跡する各反復でテーブル (details.table) を作成して更新することです。テーブル内の特定の要素が desired.iterations に達したら、ベクター rich.seq から除外して、desired.iterations を受け取っていない列のみが実際に csv ファイルに保存されるようにします。max.iterations 引数は、時間がかかりすぎる場合に備えて break() ステートメントで使用されます。
したがって、例のケースで期待していたのは、実際には変更するために何もしていないため、両方の反復で rich.seq の行がまったく同じになることです。私の問題は、rich.seq よりも長い長さのマトリックス (details.table) を比較することにあり、予期しない結果につながることは、flodel が間違いなく正しいと信じています。ただし、details.table のサイズを変更したくありません。おそらく、for ループで rich.seq を再定義すると、%in% を実装する問題を解決できるでしょうか?