# Count number of a specific element in a row

Hi,

df <- data.frame(matrix(c(1,2,3,4,4,1,2,4,4,4),ncol=5, byrow=TRUE))
df

X1 X2 X3 X4 X5
1 1 2 3 4 4
2 1 2 4 4 4

I'm sure there is an easy answer, but I can't come up with it. How do I count the number of 4's in row 1? How do I count the number of 4's in row 2?

I used mutate to add a column to the original data frame. You can use summarize if you want a separate data frame.

``````df |> rowwise() |> mutate(Count_4s = sum(c_across(X1:X5)==4))
# A tibble: 2 x 6
# Rowwise:
X1    X2    X3    X4    X5 Count_4s
<dbl> <dbl> <dbl> <dbl> <dbl>    <int>
1     1     2     3     4     4        2
2     1     2     4     4     4        3
``````

Nice!
How about if I change the data to
df <- data.frame(matrix(c(1,2,3,14,4,1,2,4,14,24),ncol=5, byrow=TRUE))
I still want to count the 4's by row, where for example 14 has a 4.

Is this right?

``````df <- data.frame(matrix(c(1,2,3,14,4,1,2,4,14,24),ncol=5, byrow=TRUE))
df
X1 X2 X3 X4 X5
1  1  2  3 14  4
2  1  2  4 14 24
library(dplyr)
library(stringr)
df |> rowwise() |>
mutate(Count_4s=sum(str_detect(c_across(X1:X5),"4")))
# A tibble: 2 x 6
# Rowwise:
X1    X2    X3    X4    X5 Count_4s
<dbl> <dbl> <dbl> <dbl> <dbl>    <int>
1     1     2     3    14     4        2
2     1     2     4    14    24        3
``````

Your solution helped me think of a non-tidy solution:

library(stringr)
df\$all <- paste0(df\$X1, df\$X2, df\$X3, df\$X4, df\$X5, pattern= "")
df\$count_4 <- str_count(df\$all, "4")

Thank you, FJCC

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.