如果多个列具有负值,则添加新列 [英] Add a new column if multiple columns have negative value
本文介绍了如果多个列具有负值,则添加新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果条件为
,我正尝试在我的数据框df1中添加一个新列- 仅选择特定列(Count1:Count3列)具有负值,则Result=&Quot;Negative&Quot;
- 如果任何一列(Count1、Count2、Count3)具有正值,则结果=正值
输入
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))
预期输出
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
推荐答案
工作:
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
这篇关于如果多个列具有负值,则添加新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文