首页 > 解决方案 > 多个ifelse语句?

问题描述

我有一个如下表,我想使用 if-else 命令向数据添加一列,我使用了如下两个命令行:

table:

 A       B        C  

G1    0.04      0.2
G2    0.02     -0.5
G3    0.9       0.1

我使用过的代码:

1)
table$DE <- 
  if (table$B < 0.05 & table$C> 0) 
{
  print("UP")
} else if (table$B < 0.05 & 
table$C < 0) {
  print("Down")
 } else {
 print("NotSig")
}

[1] "NotSig" Warning messages: 1: In if (table_UGP2$FDR_NCS_H9_KO < 0.05 & table_UGP2$logFC_NCS_H9_KO > : the condition has length > 1 and only the first element will be used 2: In if (table_UGP2$FDR_NCS_H9_KO < 0.05 & table_UGP2$logFC_NCS_H9_KO < : the condition has length > 1 and only the first element will be used

2)  table$DE <- function(table) {
  ifelse(table$B < 0.05 & table$C> 
0,"UP",ifelse(table$B < 0.05 & 
table$C < 0,"Down","NotSig"))
}

Error in rep(value, length.out = nrows) : attempt to replicate an object of type 'closure'

期望的输出:

 A       B        C    DE

G1    0.04      0.2    Up
G2    0.02     -0.5    Down
G3    0.9       0.1    NotSig

标签: rif-statement

解决方案


只是为了好玩,这里是一个没有任何ifs 或elses 的解决方案:

table <- within(tab, 
       D <- factor((B <= 0.05) * (1 + (C >= 0)), 
                   levels = 0:2,
                   labels = c("NotSig", "Down", "Up")) 
)
table

   A    B    C      D
1 G1 0.04  0.2     Up
2 G2 0.02 -0.5   Down
3 G3 0.90  0.1 NotSig

推荐阅读