I'm sure this is a really easy fix but I can't seem to find the answer... I am trying to create a column at the end of my dataframe that is a sum of the number of times a specific value (say "1") appears across that row. So for example, if I started with the following dataframe:
Data:
X1 <- c(5,1,7,8,1,5)
X2 <- c(5,0,0,2,3,7)
X3 <- c(6,2,3,4,1,7)
X4 <- c(1,1,5,2,1,7)
df <- data.frame(id,X1,X2,X3,X4)
id X1 X2 X3 X4
1 1 5 5 6 1
2 2 1 0 1 1
3 3 7 0 3 5
4 4 8 2 4 2
5 5 1 3 2 1
6 6 5 7 7 7
and I was trying to identify how many times the value "1" appears across that row, I would want the output to look like this:
id X1 X2 X3 X4 one_appears
1 1 5 5 6 1 2
2 2 1 0 1 1 3
3 3 7 0 3 5 0
4 4 8 2 4 2 0
5 5 1 3 2 1 2
6 6 5 7 7 7 0
Thanks very much in advance!
CodePudding user response:
We can use rowSums
on a logical matrix
df$one_appears <- rowSums(df == 1, na.rm = TRUE)
-output
> df
id X1 X2 X3 X4 one_appears
1 1 5 5 6 1 2
2 2 1 0 1 1 3
3 3 7 0 3 5 0
4 4 8 2 4 2 0
5 5 1 3 2 1 2
6 6 5 7 7 7 0
CodePudding user response:
df %>%
mutate(
one = rowSums(across(everything(), ~ .x == 1))
)
# A tibble: 6 × 6
id X1 X2 X3 X4 one
<int> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 5 5 6 1 2
2 2 1 0 2 1 2
3 3 7 0 3 5 0
4 4 8 2 4 2 0
5 5 1 3 1 1 3
6 6 5 7 7 7 0
CodePudding user response:
Another option using apply
with sum
:
id <- c(1:6)
X1 <- c(5,1,7,8,1,5)
X2 <- c(5,0,0,2,3,7)
X3 <- c(6,2,3,4,1,7)
X4 <- c(1,1,5,2,1,7)
df <- data.frame(id,X1,X2,X3,X4)
df$one_appear = apply(df, 1, \(x) sum(x == 1))
df
#> id X1 X2 X3 X4 one_appear
#> 1 1 5 5 6 1 2
#> 2 2 1 0 2 1 2
#> 3 3 7 0 3 5 0
#> 4 4 8 2 4 2 0
#> 5 5 1 3 1 1 3
#> 6 6 5 7 7 7 0
Created on 2023-01-18 with reprex v2.0.2