2014-07-14 2 views
3

숫자 값을 대문자로 바꾸고 싶지만 이렇게 자연스럽게 찾을 수는 없습니다. 여기에 내가 시도 내용은 다음과 같습니다R 언어 : 숫자 값의 대소 문자 바꾸기

fun <- function(x) { 
    switch(x, 
      0.2=0.1, 
      0.9=0.6) 
} 

이 하나가 컴파일하지만 더 나은 솔루션이있다 :이 구문 오류로 연결

?

fun <- function(x) { 
    y <- as.character(x) 
    switch(y, 
      "0.2"=0.1, 
      "0.9"=0.6) 
} 

답변

5

If the value of EXPR is not a character string it is coerced to integer. If this is between 1 and nargs()-1 then the corresponding element of ... is evaluated and the result returned: thus if the first argument is 3 then the fourth argument is evaluated and returned.

추가적으로 ?switch 도움말 페이지에 따르면, 도움말 페이지 만 정수 값을 수치 표현을 사용

## Numeric EXPR does not allow a default value to be specified 
## -- it is always NULL 
for(i in c(-1:3, 9)) print(switch(i, 1, 2 , 3, 4)) 

따라서 숫자 스위치를 사용하는 경우의 예를 제공 허용됩니다. 두 개의 10 진수 값이 정확히 isn't always that easy과 같으므로 허용되지 않습니다. 아마도 정수가 아닌 숫자 값을 사용하는 것보다이 특정 조건을 추적하는 더 좋은 방법이있을 것입니다.

관련 문제