I am trying to look at how often a certain value appears in a row my data frame.
For that let's look at a a test data frame:
df <-
data.frame(x1 = letters[1:5], x2 = letters[c(1,3,3,1,1)], x3 = letters[c(2,3,3,2,3)])
What I did was the following:
table(rowSums(df[, 1:3] == "c"))
with the output being:
0 1 2 3
2 1 1 1
So there are 2 rows in which "c" doesn't appear, one where it appears once, one where it appears twice and one where it appears three times.
I was wondering how one could achieve the same thing without sqare brackets and positional selection (df[, 1:3]
), but with actual variable names,
so that changing a dataframe doesn't interfere with the results.
I tried multiple versions with select()
, pull()
and filter()
or the %in% but just couldn't get it to work the same way.
Any ideas?
Kind regards, Jakob