fcas80
December 10, 2021, 3:38am
1
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?
FJCC
December 10, 2021, 3:51am
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
fcas80
December 10, 2021, 4:01am
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.
FJCC
December 10, 2021, 4:39am
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
fcas80
December 10, 2021, 8:05pm
5
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
system
Closed
December 17, 2021, 8:05pm
6
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.