I am trying to add a new column result
in my dataframe df1
, as specific columns (value1
and value2
columns) met the following conditions:
Both of them row-wisely are positive, negative or 0, or one of them is 0 and another is either negative or positive, then
result=="True"
;if row-wisely one of them are positive and another is negative or verse versa, then
result=="False"
;if row-wisely both of them are
NA
s or one of them isNA
but another is either negative or positive, thenresult=="-"
Input:
df1 <- data.frame(ID= c("ID1","ID2","ID3","ID4","ID5"), value1 = c(1.2, -1, NA, -1.5, 0), value2 = c(0.8, -1.1, -1, 1.3, 0.9))
Expected output:
df2 <- data.frame(ID= c("ID1","ID2","ID3","ID4","ID5"), value1 = c(1.2, -1, NA, -1.5, 0), value2 = c(0.8, -1.1, -1, 1.3, 0.9), result = c("True","True","-", "False", 'True'))
Out:
Any helps would be appreciated.
Reference link:
Add a new column if multiple columns have negative value
CodePudding user response:
You may try
library(dplyr)
df1 %>%
mutate(result = case_when(
is.na(value1 * value2) ~ "-",
value1 * value2 >=0 ~ "True",
T ~ "False"
))
ID value1 value2 result
1 ID1 1.2 0.8 True
2 ID2 -1.0 -1.1 True
3 ID3 NA -1.0 -
4 ID4 -1.5 1.3 False
5 ID5 0.0 0.9 True