2017-02-14 4 views
0

R 및 매트릭스 기반 스크립팅 언어에 대해 비교적 새로운 기술입니다. 이 함수는 다른 행의 내용과 비슷한 내용을 가진 각 행의 인덱스를 반환하기 위해 작성했습니다. 그것은 내가 개발하고있는 스팸 감소의 원시적 인 형태입니다.이 함수를 추가로 벡터화 할 수 있습니까?

if (!require("RecordLinkage")) install.packages("RecordLinkage") 

library("RecordLinkage") 

# Takes a column of strings, returns a list of index's 
check_similarity <- function(x) { 
    threshold <- 0.8 
    values <- NULL 
    for(i in 1:length(x)) { 
    values <- c(values, which(jarowinkler(x[i], x[-i]) > threshold)) 
    } 
    return(values) 
} 

거기에 for 루프를 완전히 피할 수있는 방법이 있습니까?

+1

@akrun 업데이트 환호 – user2228313

+0

이 @db 아니, 다른 모든 행에 대해 비교하고, x는 [I], X [-i] – user2228313

+1

어쩌면이 시도 : : 문자열이 긴 경우이 지저분 될 수있다' m = as.matrix (sapply (x, jarowinkler, x))> 임계 값; diag (m) = 0; which (rowSums (m)> 0)'테스트 할 재현 가능 데이터가 없지만 이것이 효과가 있다고 생각합니다. – dww

답변

1

sapply을 사용하여 코드를 다소 단순화 할 수 있습니다.

# some test data # 
x = c('hello', 'hollow', 'cat', 'turtle', 'bottle', 'xxx') 

# create an x by x matrix specifying which strings are alike 
m = sapply(x, jarowinkler, x) > threshold 

# set diagonal to FALSE: we're not interested in strings being identical to themselves 
diag(m) = FALSE 

# And find index positions of all strings that are similar to at least one other string 
which(rowSums(m) > 0) 
# [1] 1 2 4 5 

.l.e. 'hello', 'hollow', 'turtle'및 'bottle'의 인덱스 위치를 다른 문자열과 비슷한 것으로 반환합니다.

원하는 경우 rowSums 대신 colSums를 사용하여 명명 된 벡터를 얻을 수 있지만

which(colSums(m) > 0) 
# hello hollow turtle bottle 
#  1  2  4  5