假设我有这个数据集:
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
我该如何创建一个统计次数的列;1〃;或";2〃;显示在各列之间,看起来如下:
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
我们可以在创建的逻辑矩阵上使用rowSums
,通过循环这些值来比较这些值
df1[paste0("count_", seq_along(df1))] <- lapply(1:2,
function(x) rowSums(df1 == x))
-输出
> 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
数据
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"))
在tidyverse
-样式中:
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
如果您正在计算指定列中的数字1到n:
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
数据:
df = data.frame(
col1 = c(2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L),
col2 = c(1L, 1L, 2L, 2L, 2L, 1L, 1L, 2L)
)