简体   繁体   中英

Multiple if conditions in map from purrr

I am trying to create a new character vector in R based on the input value present in 'operator' character vector. The operator variable contains values like ">", "<" "" and NULL. I need to create a new vector like operator_id which has equivalent numeric code for the above mathematical operators. Please find the code that I wrote using for loop. However this is very time consuming and is there any other efficient way of writing this code?

for (ch in operator){
  if (ch == ""){
    #print("hi")
    operator_concept_id = append(operator_concept_id, 4172703L)
    value_as_concept_id = append(value_as_concept_id, 45884084L)
  } else if (ch == ">"){
    #print("hello")
    operator_concept_id = append(operator_concept_id, 4172704L)
    value_as_concept_id = append(value_as_concept_id, 45876384L)
  } else if (ch == "<"){
    #print("less")
    operator_concept_id = append(operator_concept_id, 4171756L)
    value_as_concept_id = append(value_as_concept_id, 45881666L)
  }
  else if(ch== "-"){
    #print("negative")
    operator_concept_id = append(operator_concept_id, 4172703L)
    value_as_concept_id = append(value_as_concept_id, 45878583L)
  } else{
    #print("nothing")
    operator_concept_id = append(operator_concept_id, 0L)
    value_as_concept_id = append(value_as_concept_id, 45881630L)
  }
}

Hopefully I got the aim right, this is a possible solution:

Operators<-c(">","<","NULL")#Did not use a real `NULL`
Numerics<-c(1234,567,8910)
purrr::map2(Operators,Numerics,function(x,y) append(x,y))

Result:

#[[1]]
#[1] ">"    "1234"

#[[2]]
#[1] "<"   "567"

#[[3]]
#[1] "NULL" "8910"

We could use a switch statement:

for (ch in operator){
  switch(ch, 
         ">"={
           #print("hello")
           operator_concept_id = append(operator_concept_id, 4172704L)
           value_as_concept_id = append(value_as_concept_id, 45876384L)   
         },
         "<"={
           #print("less")
           operator_concept_id = append(operator_concept_id, 4171756L)
           value_as_concept_id = append(value_as_concept_id, 45881666L)
         },
         "-"={
           #print("negative")
           operator_concept_id = append(operator_concept_id, 4172703L)
           value_as_concept_id = append(value_as_concept_id, 45878583L) 
         },
         {
           #print("hi")
           operator_concept_id = append(operator_concept_id, 4172703L)
           value_as_concept_id = append(value_as_concept_id, 45884084L)
         }
  )

}

Note that we cannot switch on "" , instead, I used that as the default option at the end, so anything not fitting the previous cases will execute as that option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM