Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple ifelse statement?

Tags:

r

if-statement

I have a table like below, I want to add a column to data using the if-else command, and I used two command lines as below:

table:

 A       B        C  

G1    0.04      0.2
G2    0.02     -0.5
G3    0.9       0.1

Codes that I have used:

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'

Desired output:

 A       B        C    DE

G1    0.04      0.2    Up
G2    0.02     -0.5    Down
G3    0.9       0.1    NotSig
like image 209
star Avatar asked Sep 16 '26 17:09

star


1 Answers

Just for fun, here is a solution without any ifs or 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
like image 62
Vincent Guillemot Avatar answered Sep 19 '26 08:09

Vincent Guillemot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!