Thanks to MrFlick: Using Update1 version does not work as Using .
in the rowSums
bypasses the across()
(see comment MrFlick)
Therefore we could use rowwise
with c_across
and sum
within a dplyr workflow:
Here is an example where ID == 2
:
2. Update:
data:
df <- structure(list(ID = 2L, Item1 = 2L, Item2 = 3L, Item3 = 2L, Item4 = 3L,
Newvariable = 2L), class = "data.frame", row.names = c(NA,
-1L))
code:
library(dplyr)
df %>%
rowwise() %>%
mutate(Total = sum(c_across(-ID)==2))
output:
# Rowwise:
ID Item1 Item2 Item3 Item4 Newvariable Total
<int> <int> <int> <int> <int> <int> <int>
1 2 2 3 2 3 2 3
Update1: (does not work)
Using .
in the rowSums
bypasses the across()
(see comment MrFlick)
df %>%
mutate(across(-ID), Total = rowSums(. == 2))
First answer:
We could use rowSums
:
library(dplyr)
df %>%
mutate(Total = rowSums(. == 2))
ID Item1 Item2 Item3 Item4 Newvariable Total
1 1 2 3 2 3 2 3