Lets say I have this data set:
col1 col2
1 2 1
2 1 1
3 1 2
4 1 2
5 1 2
6 1 1
7 2 1
8 2 2
How would I go about creating a column that counts the number of times either "1" or "2" appears across the columns, such that it looks like this:
col1 col2 count_1 count_2
1 2 1 1 1
2 1 1 2 0
3 1 2 1 1
4 1 2 1 1
5 1 2 1 1
6 1 1 2 0
7 2 1 1 1
8 2 2 0 2
CodePudding user response:
We may use rowSums
on a logical matrix created with value to be compared by looping over those values
df1[paste0("count_", seq_along(df1))] <- lapply(1:2,
function(x) rowSums(df1 == x))
-output
> df1
col1 col2 count_1 count_2
1 2 1 1 1
2 1 1 2 0
3 1 2 1 1
4 1 2 1 1
5 1 2 1 1
6 1 1 2 0
7 2 1 1 1
8 2 2 0 2
data
df1 <- structure(list(col1 = c(2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L), col2 = c(1L,
1L, 2L, 2L, 2L, 1L, 1L, 2L)), class = "data.frame",
row.names = c("1",
"2", "3", "4", "5", "6", "7", "8"))
CodePudding user response:
In tidyverse
-style:
library(dplyr)
library(purrr)
df1 %>%
mutate(map_dfc(1:2, ~ transmute(df1, "count_{.x}" := rowSums(across(everything()) == .x))))
# col1 col2 count_1 count_2
# 1 2 1 1 1
# 2 1 1 2 0
# 3 1 2 1 1
# 4 1 2 1 1
# 5 1 2 1 1
# 6 1 1 2 0
# 7 2 1 1 1
# 8 2 2 0 2
CodePudding user response:
If you are counting the numbers 1 to n in the specified columns:
n = 2L
inp_col = sprintf("col%d", 1L:2L)
df[sprintf("count_%d", 1L:n)] = t(apply(df[inp_col], 1L, tabulate, nbins = n))
# col1 col2 count_1 count_2
# 1 2 1 1 1
# 2 1 1 2 0
# 3 1 2 1 1
# 4 1 2 1 1
# 5 1 2 1 1
# 6 1 1 2 0
# 7 2 1 1 1
# 8 2 2 0 2
Data:
df = data.frame(
col1 = c(2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L),
col2 = c(1L, 1L, 2L, 2L, 2L, 1L, 1L, 2L)
)