我想用类似sumif的逻辑语句来改变列:
示例数据:
df <- data.frame(ID = c("A", "B", "C", "D", "E"), X = c(10, 20, 15, 0, 15), Y = c(10, 0, 10, 15, 0), Z = c(0, 10, 10, 10, 0))
df
ID X Y Z
1 A 10 10 0
2 B 20 0 10
3 C 15 10 10
4 D 0 15 10
5 E 15 0 0
我需要改变列:
但是如果X,Y和Z中存在非零值,我需要X + Y中的和为0 /空白。
因此对于第3行,X + Y + Z应该等于35,但是X + Y应该等于0 /空白。
答案 0 :(得分:1)
df %>% mutate(c1 = ifelse(X != 0 & Y != 0 & Z != 0, 0, X + Y),
c2 = X + Z,
c3 = Y + Z,
c4 = X + Y + Z)
答案 1 :(得分:0)
我用Gregor的帮助解决了这个问题:
df1 <- df %>%
mutate(XY = ifelse(X != 0 & Y != 0 & Z == 0, X + Y, 0),
XZ = ifelse(X != 0 & Y == 0 & Z != 0, X + Z, 0),
YZ = ifelse(X == 0 & Y != 0 & Z != 0, Y + Z, 0),
XYZ = ifelse(X != 0 & Y != 0 & Z != 0, X + Y + Z, 0))
谢谢!