1

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
D A
  • 11
  • 4
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Apr 08 '21 at 07:27

3 Answers3

3

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))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

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))
GKi
  • 37,245
  • 2
  • 26
  • 48
0

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

Oliver
  • 8,169
  • 3
  • 15
  • 37