我试图根据“运算符”字符向量中的输入值在R中创建一个新的字符向量。 operator变量包含“>”,“<”“”和NULL之类的值。我需要创建一个像operator_id这样的新向量,它具有上述数学运算符的等效数字代码。请找到我用于循环编写的代码。但是这非常耗时,还有其他有效的方法来编写这段代码吗?
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)
}
)
}
请注意,我们无法打开""
,相反,我在最后使用它作为默认选项,因此任何不符合先前案例的内容都将作为该选项执行。