gpt4 book ai didi

r - 使用 apply 将 R 循环转换为函数形式

转载 作者:行者123 更新时间:2023-12-01 15:46:50 24 4
gpt4 key购买 nike

我编写了一些 R 代码来解析字符串、计算子字符串的出现次数,然后填充子字符串计数表。它工作正常,但在我使用的实际数据(相当大)上它真的很慢,而且我知道其中很多是因为我使用的是循环而不是 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
}
}
}
}

谢谢。

最佳答案

一个单行,分为 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, *) 是将行列表转换为单个数据框的标准用法。

关于r - 使用 apply 将 R 循环转换为函数形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19577009/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com