I have read in an excel sheet as a dataframe that contains various numbers and characters in each row/col (with some NAs). For each row, I want to count how many occurrences of "g" there are, for example. My problem is that some cells contain something like, "g#" or "g a" or "1g", and, thus, are not being included in the count. I want to count EVERY occurrence of g, regardless of what is in the cell with it, and then add this count as a new variable to the current dataframe.
I have tried messing around with the following code, all which work for counting each occurrence of EXACTLY "g" but not simply every occurrence of "g".
My hunch is that I am looking for a regular expression to place in any of the following codes. (I searched for a few hours with no avail.) I also tried functions from the stringr package, such as str_count, but these seem to be only applicable to vectors.
oneelecsheet$countg <- rowSums(oneelecsheet == "g", na.rm = TRUE)
library(expss)
oneelecsheet$countg <- count_row_if("g", oneelecsheet)
oneelecsheet$countg <- apply(oneelecsheet, 1, function(x) length(which(x=="g")))
library(dplyr)
oneelecsheet$countg <- apply(oneelecsheet, 1, function(x) sum(x %in% "g"))