繁体   English   中英

来自purrr的map中的if条件

[英]Multiple if conditions in map from purrr

我试图根据“操作符”字符向量中存在的输入值在R中创建一个新的字符向量。 该运算符变量包含诸如“>”,“ <”“”和NULL之类的值。 我需要创建一个新的向量,如operator_id,其具有与上述数学运算符相同的数字代码。 请找到我使用for循环编写的代码。 但是,这非常耗时,还有其他有效的方法可以编写此代码吗?

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)
  }
}

希望我的目标正确,这是一个可能的解决方案:

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

结果:

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

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

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

我们可以使用switch语句:

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)
         }
  )

}

请注意,我们无法打开"" ,相反,我在最后使用了它作为默认选项,因此,不适合先前情况的所有内容都将作为该选项执行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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