2
patt<-c(`205` = FALSE, `210` = TRUE, `16` = TRUE, `2` = FALSE)    
totalobs<-0
{for (element in patt)
    if (element == TRUE){
    print (element)
    totalobs=totalobs+sum(element)
    }
print (totalobs)
}

I have a logical vector see here, of which I want to add all the values of TRUE. With the above code I am only able to add up the amount of times TRUE is present in this vector, rather than the numbers that are above each TRUE value. I am quite new to R, how would I solve this?

Janne
  • 47
  • 5
  • `sum(patt)` maybe. Please share a minimal [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) and show expected output. – markus Feb 06 '19 at 20:21
  • Thanks, I tried it and it also summed up to 10. Maybe some more information: the patt variable is generated from the mice package (md.pattern) which assigns a TRUE if a row has one NA value, and FALSE when it has no NA or more than one NA. – Janne Feb 06 '19 at 20:24
  • Please share sample data, use `dput` as shown in the link I posted earlier. – markus Feb 06 '19 at 20:26
  • Thank you. I updated my original post. – Janne Feb 06 '19 at 20:35
  • Great! What is the result you are looking for? – markus Feb 06 '19 at 20:36
  • I would like to add the TRUE values- basically add 210 and 16 in this case by an R command that adds all these values together. – Janne Feb 06 '19 at 20:37

1 Answers1

1

We can use patt to subset names(patt), convert the result to a numeric vector and finally use sum to get desired output as shown below

sum(as.numeric(names(patt)[patt]))
#[1] 226

If you need to do this kind of calculations more often then write a little function

Janne <- function(x) {
  sum(as.numeric(names(x)[x]))
}

Janne(patt)
markus
  • 25,843
  • 5
  • 39
  • 58