I am trying to add a new column "result" in my dataframe df1, if the condition is
input
df1<- data.frame(ID= c("ID1","ID2","ID3","ID4"), count1 = c(1,-1,0,-1), count2 = c(1,-1,-1,1), count3 = c(1,-1,1,-1))
expected output
df2 <- data.frame(ID= c("ID1","ID2","ID3","ID4"),count1 = c(1,-1,1,-1), count2 = c(1,-1,-1,1), count3 = c(1,-1,1,-1), result = c("positive","negative","positive","positive"))
ID count1 count2 count3 result
ID1 1 1 1 positive
ID2 -1 -1 -1 negative
ID3 1 -1 1 positive
ID4 -1 1 -1 positive
Does this work:
apply(df1,1,function(x) if(all(x > 0)) 'positive' else 'negative')
[1] "positive" "negative" "negative" "negative"
library(dplyr)
df1 %>% rowwise() %>% mutate(result = if_else(all(c_across(cols = everything()) > 0),'positive','negative'))
# A tibble: 4 x 4
# Rowwise:
count1 count2 count3 result
<dbl> <dbl> <dbl> <chr>
1 1 1 1 positive
2 -1 -1 -1 negative
3 0 -1 1 negative
4 -1 1 -1 negative
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments