如何在R中制定多个if条件?

MAP*_*APK 1 r

我有这个数据叫dft.我想将Ch1 .. Ch4添加为chrdft.我有其他条件,但似乎没有用.我的if else声明有什么问题?

dft <- structure(list(pos_coverage = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), 
    position = 1:10, neg_coverage = c(0, 0, 0, 0, 0, 0, 0, 0, 
    0, 0)), .Names = c("pos_coverage", "position", "neg_coverage"
), row.names = c(NA, 10L), class = "data.frame")


Ch1 <- 1:2
Ch2 <- 3:5
Ch3 <- 6:8
Ch4 <- 9:10

if( dft$position == Ch1){
  dft$chr <- "Ch1"
} else if (dft$position == Ch2){
  dft$chr <- "Ch2"
} else if (dft$position == Ch3){
  dft$chr <- "Ch3"
} else {dft$chr <- "Ch4"}
Run Code Online (Sandbox Code Playgroud)

Par*_*ait 5

考虑嵌套ifelse并更改==%in%:

dft$chr <- with(dft, ifelse(position %in% Ch1, "Ch1", 
                           ifelse(position %in% Ch2, "Ch2",
                                  ifelse(position %in% Ch3, "Ch3", "Ch4")
                                 )
                           )
               )
Run Code Online (Sandbox Code Playgroud)

Rextester演示