Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Counting the occurrence of a word but only once per row (R)

I want to count the number of times a word appears but only once per row. How do I complete the code?

library(stringr)

var1 <- c("x", "x", "x", "x", "x", "x", "y", "y", "y", "y")
var2 <- c("x", "x", "b", "b", "c", "d", "e", "y", "g", "h")
var3 <- c("x", "x", "b", "b", "c", "d", "e", "y", "g", "h")
data <- data.frame(cbind(var1, var2, var3))

sum(str_count(data, "x"))

The result should be 6.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The following should do the trick:

sum(rowSums(data == "x") >= 1) # Thanks Maël
# [1] 6

which will check if there is at least one value per row (rowSums()) and add all the rows with 1+ up using sum()

Or alternatively (per Antreas’s comment so it is not missed):

length(which(rowSums(data == "x") != 0)) # Thanks to Antreas Stefopoulos

Which counts the number of non-zero rows with.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading