2014-05-12 3 views
1

결과 데이터 프레임의 값을 변경하기 위해 Hadley Wickham (https://stackoverflow.com/a/12829731/2872891)의 답변에서 권장하는 stringr 기반 함수를 사용합니다. 나는 df을 끝으로 return (df)으로 변경하는 것을 제외하고는 그대로 함수를 그대로 두었습니다. 그러나, 나는 이상한 행동을 보았고, 그 이유가 무엇인지 모르겠습니다. replace_all의 후속 호출, 특히 # 3 및 # 4 호출은 원래 데이터 (http:mailto:)를 복구하지 않습니다. A 재현 가능한 예이옵니다.stringr 기반 함수의 이상한 동작

데이터 (데이터의 한 기록) :

는 GitHub의에이 요점 참조하십시오

: https://gist.github.com/abnova/1709b1e0cf8a57570bd1#file-gistfile1-r

코드을 (간결함을 위해, 나는 자세한 explainations 내 주석을 제거)

DATA_SEP <- ":" 

rx <- "([[:alpha:]][^.:]|[[:blank:]])::([[:alpha:]][^:]|[[:blank:]])" 
results <- gsub(rx, "\\[email protected]@\\2", results) 
results <- gsub(": ", "[email protected]#", results) # should be after the ::-gsub 
results <- gsub("http://", "http//", results) 
results <- gsub("mailto:", "[email protected]", results) 

results <- gsub("-\\r\\n", "-", results) # order is important here 
results <- gsub("\\r\\n", " ", results) 

results <- gsub("\\n:gpl:962356288", ":gpl:962356288", results) 

results <- readLines(textConnection(unlist(results))) 
numLines <- length(results) 
results <- lapply(results, function(x) gsub(".$", "", x)) 

data <- read.table(textConnection(unlist(results)), 
        header = FALSE, fill = TRUE, 
        sep = DATA_SEP, quote = "", 
        colClasses = "character", row.names = NULL, 
        nrows = numLines, comment.char = "", 
        strip.white = TRUE) 

replace_all(data, fixed("[email protected]#"), ": ") 
replace_all(data, fixed("@@"), "::") 
replace_all(data, fixed("http//"), "http://") 
replace_all(data, fixed("[email protected]"), "mailto:") 
결과 - 실제 :

> data$V3 
[1] "http//www.accessgrid.org/" 
> data$V17 
[1] "http//[email protected]@lists.sourceforge.net" 

결과 - 예상은 :

> data$V3 
[1] "http://www.accessgrid.org/" 
> data$V17 
[1] "http://mailto:[email protected]" 

나는 어떤 도움 및/또는 조언을 감사하겠습니다.

+0

'fixed'는 패턴을 정규 문자열로 일치시킵니다. replace_all에서 패턴을 제거하고 어떤 일이 일어나는지보십시오. 근처에 컴파일러가 없습니다. – hwnd

+0

@ hwnd : 저는 고정 된 문자열을 검색하고 대체하기 위해 의도적으로'fixed'를 사용했습니다. 그러나, 필사적으로, 나는 그것을 시도하고보고 할 것이다. 감사! –

+0

@ hwnd : 방금 당신의 제안을 시도했습니다. 불행히도 도움이되지 않았습니다. 결과는 '고정'과 동일합니다. –

답변

0

. 나는 고정 된 코드를 빨리 테스트했고 내 생각을 확증했다. 각 후속에 대해 이 필요합니다.replace_str으로 전화를 걸어 번으로 결과를 다시 저장합니다. 이전에 각각의 호출에서 반환 된입니다. 따라서, 고정 된 코드는 다음과 같습니다

# Now we can safely do post-processing, recovering original data 
data <- replace_all(data, fixed("[email protected]#"), ": ") 
data <- replace_all(data, fixed("@@"), "::") 
data <- replace_all(data, fixed("http//"), "http://") 
data <- replace_all(data, fixed("[email protected]"), "mailto:") 

다시 한번 감사는이 문제를 알아 내기 위해 나에게 도움이되는 가치있는 제안을 @hwnd 할 수 있습니다.

2

나는 이것을 테스트하여 replace_all 번을 여러 번 호출하여 교체 문제를 발견했습니다. 당신이 결과 이후에 아무것도에 replace_all 호출을 할당하지 이기 때문에

replace_all(data, fixed("[email protected]#"), ": ") 
replace_all(data, fixed("@@"), "::") 
replace_all(data, fixed("http//"), "http://") 
replace_all(data, fixed("[email protected]"), "mailto:") 

이유 당신이 예상 출력을 볼 수 없습니다입니다. 그것은

data <- replace_all(data, fixed("[email protected]#"), ": ") 
data <- replace_all(data, fixed("@@"), "::") 
data <- replace_all(data, fixed("http//"), "http://") 
data <- replace_all(data, fixed("[email protected]"), "mailto:") 
data 

.. 교체에 대한 하나의 호출로 통해 패턴과 교체 및 루프를 포함하는 벡터를 생성하는 것입니다 stringr를 사용하지 않고이 작업을 수행하는 또 다른 방법이 될 것이다.

re <- c('[email protected]#', '@@', 'http//', '[email protected]') 
val <- c(': ', '::', 'http://', 'mailto:') 

replace_all <- function(pattern, repl, x) { 
    for (i in 1:length(pattern)) 
     x <- gsub(pattern[i], repl[i], x, fixed=T) 
     x 
} 
replace_all(re, val, data) 

출력 거의 @hwnd에 의해 제안 대안 (gsub 기반) 구현, 내 원래의 코드와 함께 문제가 무엇인지 깨달았을 완료 한 후

[3] "http://www.accessgrid.org/" 
[17] "http://mailto:[email protected]" 
+0

도와 주셔서 감사합니다. 이것은 매우 좋게 보이고 유용 할 것입니다. 내 코드의 다른 부분에서'stringr' 패키지를 사용하는 동안이 패키지를이 장소에서 사용하지 못할 수도 있습니다. (버그를 발견 한 것 같지 않습니다.) 그럼에도 불구하고'replace_all' 함수를 사용해야하는데, 결과 데이터 프레임의 모든 적합한 필드에서 검색과 대체를 수행해야하므로'gsub' 등을 사용하도록 수정해야합니다. –

+0

지금까지 오프라인 상태였습니다. 업데이트를 보았습니다. 도와 주셔서 정말 감사합니다! 내 테스트는 설명을 확인합니다 (연속적으로 전화를 걸 때 실패 함). 나는이 코드를'gsub'를 사용하도록 바꿀 것입니다. 그러나 @hadley가'stringr' 패키지의 이런 행동에 대해 논평 할 수 있기를 바랍니다. 만약 이것이 결함이라면 그것을 인정하고 고쳐주세요. –

+0

@AleksandrBlekh 나는 코드를 재검토하고 어제 밤에 내가 그 대답을 업데이트했다고 생각했다. – hwnd