Reputation: 775
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
Upvotes: 2
Views: 84
Reputation: 2987
I think you want to use ifelse
instead.
table <- read.table(header = TRUE, text = "A B C
G1 0.04 0.2
G2 0.02 -0.5
G3 0.9 0.1")
table$DE <- ifelse(table$B < .05 & table$C> 0, "Up",
ifelse(table$B < .05 & table$C < 0, "Down", "NotSig"))
Which produces:
A B C DE
1 G1 0.04 0.2 Up
2 G2 0.02 -0.5 Down
3 G3 0.90 0.1 NotSig
Upvotes: 3
Reputation: 13319
With dplyr
:
df %>%
mutate(DE=ifelse(B < 0.05 & C > 0, "UP",
ifelse(B < 0.05 & C <0,"Down","Notsig")))
Or using case_when
:
df %>%
mutate(DE=case_when(B < 0.05 & C>0 ~ "UP",
B<0.05 & C<0 ~ "Down",
TRUE ~ "Notsig"))
Result:
A B C DE
1 G1 0.04 0.2 UP
2 G2 0.02 -0.5 Down
3 G3 0.90 0.1 Notsig
Data:
df <-structure(list(A = structure(1:3, .Label = c("G1", "G2", "G3"
), class = "factor"), B = c(0.04, 0.02, 0.9), C = c(0.2, -0.5,
0.1)), class = "data.frame", row.names = c(NA, -3L))
Upvotes: 3
Reputation: 3429
Just for fun, here is a solution without any if
s or else
s:
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
Upvotes: 4