我编写了一些 R 代码来解析字符串,计算子字符串的出现次数,然后填充子字符串计数表。它工作得很好,但是在我使用的实际数据(非常大)上真的很慢,而且我知道其中很多是因为我使用的是循环而不是 apply 系列中的函数。我一直在尝试将此代码转换为功能形式,但我没有任何运气,有人可以帮忙吗?我最大的问题是我想不出一种方法来使用列名来匹配 apply 构造中的值。这是带有一些玩具数据的代码:
#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
}
}
}
}
谢谢。