条件表达式if和or

时间:2014-02-07 13:02:02

标签: r

我有以下表达式

motherW 

结果只能是以下列表中的一个元素

s2,s4,s6,s8,s10,s12,s14,s16,haar,d2,d4,d6,d8,d10,d12,d14,d16,d18,c6,c12,c18,c24,
c30,l4,l6,l14,l18

我想有一个像下面那样的条件表达式(产生错误。我相信是使用or / ifesle)

B<-If(motherW=="s2" | "s4" | "s6" | "s8" | "s10" | "s12" | "s14" | "s16") 8 ifelse  
(mother=="haar" | "d2" | "d4" | "d6" | "d8" | "d10" | "d12" | "d14" | "d16" | "d18") 9 
ifelse (motherW=="c6" | "c12" | "c18" | "c24" | "c30")) 5 ifelse (c(motherW=="l2" | "l4" 
| "l6" | "l14" | "l18") 5 else 0

其中可以根据母亲的结果提供以下任何结果 - 如果s系列8如果是d系列9,如果c系列5如果是l系列5.

3 个答案:

答案 0 :(得分:2)

以下是使用ifelse的正确方法:

B <- if (motherW %in% c("s2", "s4", "s6", "s8", "s10", "s12", "s14", "s16")) {
  8
} else {
  if (motherW %in% c("haar", "d2", "d4", "d6", "d8", "d10", "d12", "d14", "d16", "d18")) {
    9
  } else {
    if (motherW %in% c("c6", "c12", "c18", "c24", "c30", "l2", "l4", "l6", "l14", "l18")) {
      5
    } else {
      0
    }
  }  
}

更新

更短的方法是:

tab <- tab <- c(s = 5, d = 9, h = 9, c = 5, l = 5)
sus <- substr(motherW, 1, 1)
B <- if (any(sus == names(tab))) tab[sus] else 0

答案 1 :(得分:2)

您的语法不正确。首先,你需要编写像

这样的OR条件
motherW=="s2" | motherW=="s4" | ...

您可以使用%in%

而不是像这样写出来

使用嵌套ifelse条件的一种可能解决方案是

B <- ifelse(motherW %in% c("s2","s4","s6","s8","s10","s12","s14","s16"),
    8,
    ifelse(motherW %in% c("haar","d2","d4","d6","d8","d10","d12","d14","d16","d18"),
        9,
        ifelse(motherW %in% c("c6","c12","c18","c24","c30"),
            5,
            ifelse(motherW %in% c("l2","l4","l6","l14","l18"), 5, 0))))

答案 2 :(得分:1)

你可以试试这个:

B <- 8*(motherW %in% c("s2","s4","s6","s8","s10","s12","s14","s16"))+
     9*(motherW %in% c("haar","d2","d4","d6","d8","d10","d12","d14","d16","d18"))+
     5*(motherW %in% c("c6","c12","c18","c24","c30"))+
     5*(motherW %in% c("l2","l4","l6","l14","l18"))

这是有效的,因为R在数学运算中将TRUEFALSE转换为1和0。由于您的列表是非重叠的,您可以将每个TRUE / FALSE语句乘以它应该在该列表中获得的数字,如果它不在任何列表中,B将得到0。 / p>