2014-06-16 2 views
2

이 문자열이 있습니다.paste0 또는 붙여 넣기가 실패하면 r에 특수 문자가 표시됩니다.

temp <- "this is Mapof ttMapof qwqqwMApofRt it" 

출력으로 가져와야합니다.

"this is Mapof (Mapof) ttMapof (Mapof) qwqqwMapofRt it" 
나는이 일을 오전

: (! 완벽한 아무 문제)를

temp <- gsub('Mapof\\b', 'Mapof (Mapof)', temp)  #code line 1 

"this is Mapof (Mapof) ttMapof (Mapof) qwqqwMapofRt it" 

그러나 문제는 내가 벡터에서 '패턴'과 '교체'를 가지고 가야하기 때문에 내가 직접이 작업을 수행 할 수 없다 . '패턴'그 벡터의 '교체'를 추출 후 그래서, 나는 지금은 정확한 코드 라인 1 위 얻을하려면 다음과 같이 붙여 넣기()를 사용하고

inc_spelling <- "Mapof"  #(pattern) 
cor_spelling <- "Map of" #(replacement) 

을 다음과 같이 보관하지만, 그것을 일어나지 않는다. 직접보십시오. 여기서 무슨 일이 일어나는거야?

txt <- paste0("temp <- gsub('",inc_spelling,"\\b','",inc_spelling," (",cor_spelling,")'"," ,temp)") 

txt 

"temp <- gsub('Mapof\\b','Mapof (Map of)' ,temp)" 

eval(parse(text=txt)) 

temp 

"this is Mapof ttMapof qewqeqwMapofdffd it" 

실패합니다! 왜 그런가? 나는 그 버그를 알아낼 수 없다! paste()에서이 작업을 수행 할 수없는 경우 다른 대안을 제안하십시오. 감사!

답변

1

eval(parse()) (프로 팁 : 요구 사항에 맞게 @ MadScone의 대답을 수정하지 마십시오.) 더 많은 이스케이프가 필요합니다 (즉, 원래 이스케이프는 물론 이스케이프도 이스케이프해야합니다. 원래의 탈출구.이게 얼마나 미치는지 아십니까?

txt <- paste0("temp <- gsub('",inc_spelling,"\\\\b','", 
       inc_spelling," (", 
       cor_spelling,")'"," ,temp)") 
print(eval(parse(text=txt))) 
#[1] "this is Mapof (Map of) ttMapof (Map of) qwqqwMApofRt it" 
5

시도한 해결책이 더 복잡 할 필요가 있습니다.

gsub(paste0(inc_spelling, '\\b'), cor_spelling, temp) 

또는 이것은 당신이 뭘 하려는지되지 않습니다 : 당신은 gsub()에 직접 벡터 인수를 제공 할 수 있습니까?

관련 문제