R sapply循环替换for循环 [英] R sapply loop to replace for loop
问题描述
之前,我已经成功地将 for循环切换为 sapply循环, 而且我知道(system.time())它们更快.
I have successfully switched for loops to sapply loops before, and I know for a fact (system.time()) that they are faster.
但是我的思想仍然以for循环的方式工作...
BUT my mind still works in a for loop way...
请帮助我将其转换为for循环大小写:
Please help me to convert this for loop case:
names.list <- c("Anna", "Ana", "Albert", "Albort", "Rob", "Robb", "Tommy", "Tommie")
misspell.list <- c("Anna", "Albort", "Robb", "Tommie")
fix.list <- c("Ana", "Albert", "Rob", "Tommy")
for(i in 1:length(fix.list)) {
names.list[which(names.list == misspell.list[i])] <- fix.list[i]
}
names.list
到sapply()
到目前为止,我得到了:
So far, I got:
sapply(seq_along(fix.list), function(x)
names.list[which(names.list == misspell.list[x])] <- fix.list[x]
)
但是它只会返回原始向量.
But it only returns me the original vector.
谢谢!
misspell.list和fix.list由adist()波纹管自动创建,原始名称.list具有665个元素.我的for()解决方案返回length(unique(names.list))
= 653个元素
the misspell.list and fix.list were created automatically by adist() bellow and the original names.list has 665 elements. My for() solution returns length(unique(names.list))
= 653 elements
# will do another sapply() substitution here soon
for(i in 1:(length(names.list)-1)) {
distancias[i] <- adist(names.list[i], names.list[i+1])
}
# fix list
misspell.list <- names.list[which(distancias < 2)]
fix.list <- names.list[which(distancias < 2) +1]
谢谢您,现在我是 sapply霸主,我在这里只是为了展示与adist()一起使用的其他 for-sapply 替代方法
EDIT 2: thanks to you, now I'm a sapply overlord and I'm here just to show my other for-sapply substitution used with adist()
nomes <- sort(unique(names.list))
distancias <- rep(10, length(nomes))
#adist() for finding misspelling
sapply(seq_along(nomes),
function(x) {
if(x<length(nomes)) {
distancias[x] <<- adist(nomes[x], nomes[x+1])
}
}
)
# fix list
misspell.list <- names.list[which(distancias < 2)]
fix.list <- names.list[which(distancias < 2) +1]
您已经知道的另一部分,再次感谢!
The other part you already know, thanks again!
推荐答案
使用match
的解决方案要好得多,但是就您要尝试执行的操作而言,这将起作用.首先,您不需要which
.您还需要使用<<-
运算符告诉循环中定义的内部函数使用全局环境,而不是其自己的局部环境-否则,它不会更改names.list
,而只会更改其副本.
The solution using match
is much better, but in terms of what you were trying to do, this will work. Firstly, you don't need the which
. You also need to use the <<-
operator to tell the internal function defined within the loop to use the global environment rather than its own local one - otherwise it does not change names.list
, only its copy.
sapply(seq_along(fix.list), function(x)
names.list[names.list == misspell.list[x]] <<- fix.list[x]
)
names.list
[1] "Ana" "Ana" "Albert" "Albert" "Rob" "Rob" "Tommy" "Tommy"
这篇关于R sapply循环替换for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!