데이터를 정리하기 위해 변수 목록을 가져 와서 문자열 목록을 빈 문자열로 바꾸는 함수를 작성하고 있습니다. 문제를 해결하는 코드가 있지만 가변 길이 문자열 목록을 인수로 사용하는 방법을 배우고 싶습니다.
간단한 버전을 이해하기 위해 다음은 myval1 및 myval2의 "X"를 빈 문자열로 대체하고 다음과 같이 호출됩니다.
replace_string_with_empty myval1 myval2, code("X")
코드는
capture program drop replace_string_with_empty
program replace_string_with_empty
syntax varlist(min=1), Code(string)
foreach var in `varlist' {
replace `var' = "" if `var' == "`code'"
}
end
하지만 코드가 여러 개 있으면 어떻게 되나요? 이 작업을 수행하는 더 깨끗한 방법이있을 수 있다는 사실을 잊고 이것을 다음과 같이 부르고 싶습니다.
replace_string_with_empty myval1 myval2, codes("X" "NONE")
하지만 구문 명령 등에서 유형을 파악할 수 없습니다. 예를 들어 다음은 작동하지 않습니다.
capture program drop replace_string_with_empty
program replace_string_with_empty
syntax varlist(min=1), Codes(namelist)
foreach var in `varlist' {
foreach code in `codes' {
replace `var' = "" if `var' == "`code'"
}
}
end
어떤 아이디어? (다시 말하지만,이 정확한 문제를 해결하는 더 좋은 방법이 있다고 확신하지만 syntax
다른 작업에도이 방법을 사용하는 방법을 알아 내고 싶습니다 .
여기에 한 가지 접근 방식의 간단한 예가 있습니다. 이 asis
옵션은 따옴표 만 남겨 두지 만 null로 다시 코딩 할 문자열을 참조 할 때 복합 따옴표를 사용해야합니다.
capture program drop replace_string_with_empty
program replace_string_with_empty
syntax varlist(min=1 string), Codes(string asis)
tokenize `"`codes'"'
while "`1'" != "" {
foreach var of varlist `varlist' {
replace `var' = "" if `var'==`"`1'"'
}
macro shift
}
end
sysuse auto, clear
clonevar make2=make
replace_string_with_empty make*, codes("AMC Concord" "AMC Spirit" "Audi 5000")
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다