代码之家  ›  专栏  ›  技术社区  ›  MAPK

如何在R中表示多个if条件?

r
  •  1
  • MAPK  · 技术社区  · 7 年前

    我把这些数据叫做 dft . 我想添加Ch1。。甲烷砷 chr 列在 密度泛函 . 我有if-else的情况,但似乎不起作用。我下面的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"}
    
    3 回复  |  直到 7 年前
        1
  •  5
  •   Parfait    7 年前

    考虑嵌套 ifelse 改变 == %in%

    dft$chr <- with(dft, ifelse(position %in% Ch1, "Ch1", 
                               ifelse(position %in% Ch2, "Ch2",
                                      ifelse(position %in% Ch3, "Ch3", "Ch4")
                                     )
                               )
                   )
    

    Rextester demo

        2
  •  3
  •   akrun    7 年前

    更好的选择是使用 stack 然后做一个连接

    library(tidyverse)
    stack(mget(paste0("Ch", 1:4))) %>% 
       right_join(dft, by = c("values" = "position")) %>%
       rename(chr = ind)
    #   values chr pos_coverage neg_coverage
    #1       1 Ch1            0            0
    #2       2 Ch1            0            0
    #3       3 Ch2            0            0
    #4       4 Ch2            0            0
    #5       5 Ch2            0            0
    #6       6 Ch3            0            0
    #7       7 Ch3            0            0
    #8       8 Ch3            0            0
    #9       9 Ch4            0            0
    #10     10 Ch4            0            0
    
        3
  •  1
  •   jay.sf    7 年前

    ifelse() 你可以考虑你的数据的子集。

    dft$chr <- NA
    dft$chr[dft$position %in% Ch1] <- "Ch1"
    dft$chr[dft$position %in% Ch2] <- "Ch2"
    dft$chr[dft$position %in% Ch3] <- "Ch3"
    dft$chr[dft$position %in% Ch4] <- "Ch4"
    

    用一个 lapply()

    test.set <- ls(pattern="Ch")
    # # or
    # test.set <- paste0("Ch", 1:4)
    
    l <- lapply(test.set, function(x) {
      sub <- dft$position %in% get(x)
      dft$chr[sub] <- x
      dft[sub, ]
      })
    

    后果

    > do.call(rbind, l)
       pos_coverage position neg_coverage chr
    1             0        1            0 Ch1
    2             0        2            0 Ch1
    3             0        3            0 Ch2
    4             0        4            0 Ch2
    6             0        6            0 Ch3
    7             0        7            0 Ch3
    8             0        8            0 Ch3
    9             0        9            0 Ch4
    10            0       10            0 Ch4