2012-04-03 13 views
7

En R, estoy definiendo la función lengths en función del valor de un parámetro establecido previamente:El uso de un if-else para definir una función condicional en `R`

if(condition == 1){ 
    lengths <- function(vector) { 
     n <- ceiling(length(vector)/2) 
    } 
} 
else if(condition == 2){ 
    lengths <- function(vector) { 
     n <- length(vector) 
    } 
} 
else if(condition == 3){ 
    lengths <- function(vector) { 
     n <- length(vector)*2 
    } 
} 
else{ 
    lengths <- function(vector) { 
     n <- length(vector)+10 
    } 
} 

Definir una función condicional en De esta manera parece un poco ... desordenado. ¿Hay una mejor manera?

+2

Daft pregunta, pero ¿por qué no tener una función 'lengths' que toma' condición' como argumento y hace algo sensato? – csgillespie

+1

Pruebe '? Switch' quizás? – BenBarnes

Respuesta

9

Usted podría utilizar switch:

lengths <- function(vector, condition) { 
    switch(condition, 
    ceiling(length(vector)/2), 
    length(vector), 
    length(vector)*2, 
    length(vector)*+10) 
} 

Esta función proporciona un comportamiento más parecido a su ejemplo de código:

lengths <- function(vector, condition) { 
    switch(as.character(condition), 
    `1`=ceiling(length(vector)/2), 
    `2`=length(vector), 
    `3`=length(vector)*2, 
    length(vector)*+10) 
} 

... y esta función será definida por el valor de condition:

condition <- 1 
lengths <- switch(as.character(condition), 
    `1`=function(vector) ceiling(length(vector)/2), 
    `2`=function(vector) length(vector), 
    `3`=function(vector) length(vector)*2, 
    function(vector) length(vector)*+10) 
lengths 
# function(vector) ceiling(length(vector)/2) 
0

Un truco rápido basado en la sugerencia de CSGillespie:

length.lut <- cbind(c(0.5,1,2,1,),c(0,0,0,10)) 

lengths <- function(vector, condition) vector*length.lut[condition,1] + length.lut[condition,2] 
Cuestiones relacionadas