Reputation: 21
i'm trying to sum all the columns with if else condition replaced null values with 999 if not 999 it should add all columns can some one tell better one, i'm getting wrong value by using this,
like need to add sum of columns and then finally add the sum of all columns
sum((A1a(i)+A2b(i)))
sum((ifelse((df$A1a!= 999), df$A1a,0)+
ifelse((df$A2b!= 999), df$A2b,0)+
ifelse((df$A3c!= 999), df$A3c,0))
example:
A B C D
# 1 4 7 10
# 2 5 8 11
# 1 3 1 1
if B!=1 (4+5+3)
if C!=1 then add (7+8) for c and
if D! = 1for (10+11)
finally (12+15+21)=48
Upvotes: 1
Views: 416
Reputation: 39717
You can use the condition !=1
to subset and sum
the result:
y <- x[-1]
#y <- x[c("B","C","D")] #Alternativ
sum(y[y!=1])
#[1] 48
Data
x <- data.frame(A=c(1,2,1), B=c(4,5,3), C=c(7,8,1), D=c(10,11,1))
Upvotes: 1
Reputation: 389185
You can use :
cols <- c('A', 'B', 'C', 'D')
sum(df[cols] * (df[cols] != 1))
#[1] 50
df != 1
would return TRUE
/FALSE
value which is multiplied by df
so all the 1's are turned to 0 and rest of them are kept as it is.
data
df <- structure(list(A = c(1L, 2L, 1L), B = c(4L, 5L, 3L), C = c(7L,
8L, 1L), D = c(10L, 11L, 1L)), class = "data.frame", row.names = c(NA, -3L))
Upvotes: 3
Reputation: 8592
You could convert it to a numeric vector
sum(as.matrix(df)[df != 999])
There's no need to convert to 999
however so you could do
sum(as.matrix(df)[is.na(df)])
and keep the na's
Upvotes: 0