私は、米国企業の収益に関する月次観測からなるデータセットを持っています。NA以外の観察が一定数未満のすべての企業をサンプルから除外しようとしています。
を使用してやりたいことができましforeach
たが、データセットが非常に大きく、これには長い時間がかかります。これは、私が望んでいたことをどのように達成したかを示し、うまくいけば私の目標を明確にする実用的な例です
#load required packages
library(data.table)
library(foreach)
#example data
myseries <- data.table(
X = sample(letters[1:6],30,replace=TRUE),
Y = sample(c(NA,1,2,3),30,replace=TRUE))
setkey(myseries,"X") #so X is the company identifier
#here I create another data table with each company identifier and its number
#of non NA observations
nobsmyseries <- myseries[,list(NOBSnona = length(Y[complete.cases(Y)])),by=X]
# then I select the companies which have less than 3 non NA observations
comps <- nobsmyseries[NOBSnona <3,]
#finally I exclude all companies which are in the list "comps",
#that is, I exclude companies which have less than 3 non NA observations
#but I do for each of the companies in the list, one by one,
#and this is what makes it slow.
for (i in 1:dim(comps)[1]){
myseries <- myseries[X != comps$X[i],]
}
どうすればこれをより効率的に行うことができますか? data.table
同じ結果を得る方法はありますか?