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

时间:2019-01-28 18:35:57

标签: r

我将此数据称为dft。我想将Ch1 .. Ch4添加为chr中的dft列。我有其他条件,但似乎不起作用。我的以下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 个答案:

答案 0 :(得分:5)

考虑嵌套ifelse并将==更改为%in%

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

Rextester demo

答案 1 :(得分:3)

一个更好的选择是使用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

答案 2 :(得分:1)

为避免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