2

文字列を解析し、部分文字列の出現回数をカウントし、部分文字列カウントのテーブルに入力する R コードをいくつか作成しました。それは正常に動作しますが、私が使用している実際のデータ (かなり大きい) では非常に遅く、適用ファミリの関数ではなくループを使用しているためです。私はこのコードを機能的な形にしようとしてきましたが、うまくいきません。誰か助けてもらえますか? 私の最大の問題は、列名を使用して適用構造内の値を一致させる方法がわからないことです。おもちゃのデータを含むコードは次のとおりです。

#Create toy data, list of unique substrings
code_frame<-matrix(c(c('a|a|b|c|d'),c('a|b|b|c|c'),c('a|b|c|d|d')),nrow=3,ncol=1)   
all_codes_list<-c('a','b','c','d')

#create data frame with a column for each code and a row for each job
code_count<-as.data.frame(matrix(0, ncol = length(all_codes_list), nrow = nrow(code_frame)))
colnames(code_count)<-all_codes_list

#fill in the code_count data frame with entries where codes occur
for(i in 1:nrow(code_frame)){
    test_string<-strsplit(code_frame[i,1],split="|",fixed=TRUE)[[1]]
    for(j in test_string){
        for(g in 1:ncol(code_count)){
            if(j == all_codes_list[g]){
                code_count[i,g]<-code_count[i,g]+1
                }
            }
        }
    }

ありがとう。

4

3 に答える 3

5

3行に分割されたワンライナー:

do.call(rbind,
        lapply(strsplit(code_frame[,1], "|", fixed=TRUE),
               function(x) table(factor(x, levels=all_codes_list))))

strsplitはベクトル化されているため、すべての行に外側のループは必要ありません。内部ループは基本的に、各コードの出現回数をカウントアップしています。これはtable. 最後に、do.call(rbind, *)は行のリストを 1 つのデータ フレームに変換するための標準的なイディオムです。

于 2013-10-24T22:07:06.033 に答える