Search code examples
rloopsclassoop

Setting object class based on vector length


I have the following problem - I have a vector, populated with user input, on which I want to perform certain operations using a custom function. I want to use a generic function, methods of which differ according to the length of the input vector. It'd be slower and clumsier to write a long series of if statements (if vector length = x do this, else if = y do that, etc).

So, my question is, what would be the best way to assign a class to the user input vector object on the basis of its length, without using if statements to check length? Could I create a lookup table which the program uses to assign a class on the basis of vector length with only one check instead of many if statements?

I can implement this as a series of if loops:

input<-scan(what=numeric())

if (length(input)==1){
class(input)<-"classone"
}
else{
if (length(input)==2){
class(input)<-"classtwo"
}
else{
if... et cetera
}

But this is, obviously, very slow, and makes for a huge non-modular block of code.


Solution

  • You could create a vector of the class names and use the length(input) as the index to the mapped name:

    cnames <- c('classone', 'classtwo', 'classthree', 'classfour')
    idx <- length(input)
    class(input) <- cnames[idx]