来自purrr

时间:2019-03-15 04:26:46

标签: r for-loop purrr

我试图根据'operator'字符向量中存在的输入值在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)
  }
}

2 个答案:

答案 0 :(得分:0)

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

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"

答案 1 :(得分:0)

我们可以使用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)
         }
  )

}

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