使用ifelse匹配R中的向量

时间:2016-02-26 09:32:30

标签: r

我很困惑为什么这不起作用..?

getArea <- function(x){

  x <- sapply(strsplit(as.character(x), "_"), "[[", 2)
  x <- substr(x,1,2)

  out <- ifelse( x == "PL", x <- "PO",
      ifelse( x == "PH", x <- "PO",
       ifelse( x == "CM", x <- "CP",
        ifelse( x == "EP", x <- "PE",
         ifelse( x == "EW", x <- "PE",
          ifelse( x == "VD", x <- "VM",
           ifelse( x == "VE", x <- "VM",
            ifelse( x == "BA", x <- "VM",
             ifelse( x == "TP", x <- "YD",
              x <- "NA")))))))))
  x <- out
}

p <- c("aa_VD","aa_CM","aa_PH","aa_PL4","aa_EP","aa_EW","aa_VE1","aa_TP","aa_VA")
Areas <- getArea(p)

它应匹配并返回匹配的向量...但它只看到ifelse选项列表中的第一个匹配并为所有其他元素带回N ..

2 个答案:

答案 0 :(得分:1)

这是一个名为vectorelements的解决方案:

L <- c(PL="PO", PH="PO", CM="CP", EP="PE",
       EW="PE", VD="VM", VE="VM", BA="VM", TP="YD")
p <- c("aa_VD","aa_CM","aa_PH","aa_PL4","aa_EP","aa_EW","aa_VE1","aa_TP","aa_VA")                            
Areas <- L[substr(p, 4,5)]

答案 1 :(得分:0)

根据您提出的问题,我根据akrun的评论稍微清理了您的功能。

getArea <- function(x) {
      x <- sapply(strsplit(as.character(x), "_"), "[[", 2)
      x <- substr(x, 1, 2)

      out <- ifelse(x %in% c("PL", "PH"), "PO",
               ifelse(x == "CM",  "CP",
                 ifelse(x %in% c("EP", "EW") ,  "PE",
                   ifelse(x %in% c("VD", "VE", "BA"), "VM",
                     ifelse(x == "TP",  "YD", NA)
                           ))))
      return(out)
}

p <- c("aa_VD","aa_CM","aa_PH","aa_PL4","aa_EP","aa_EW","aa_VE1","aa_TP","aa_VA")
getArea(p)
[1] "VM" "CP" "PO" "PO" "PE" "PE" "VM" "YD" NA