R中所有可能性的频率计数

时间:2018-12-09 19:18:54

标签: r

我想分析数据集的频率计数。 我有6个球,编号为1到6。 从包装盒中取出3个球,无需替换,并标明数字。 将3个球放回盒子中,并将该过程重复5次。 我想分析一个数字,两个数字和三个数字的频率计数。 一个号码 1- 2 3 4 5 6- 两个数字 (1,2) (1,3) 6C2 = 15个组合 三个数字 (1,2,3) (1,2,4) 6C3 = 20个组合

有我的数据集。

df = as.data.frame(rbind(c(1,3,5), c(3,4,5), c(2,4,6), c(1,3,6), c(2,4,5)))
colnames(df) = c("num1","num2","num3")

  num1 num2 num3
1    1    3    5
2    3    4    5
3    2    4    6
4    1    3    6
5    2    4    5

我是R新手。我们将不胜感激。 谢谢, 巴巴吉D K R

1 个答案:

答案 0 :(得分:0)

这是一些非常精致的解决方案,但是可以完成工作:

library(tidyverse)

#One number

one_numb <- combn(names(df), 1, simplify = FALSE)

result <- list()

for(i in 1:length(one_numb)) {
 result[[i]] <- df %>%
  mutate(comb = paste0(!!as.symbol(one_numb[[i]][1]))) %>%
  select(comb)
}

bind_rows(result) %>%
 group_by(comb) %>%
 tally()

  comb      n
  <chr> <int>
1 1         2
2 2         2
3 3         3
4 4         3
5 5         3
6 6         2

#Two numbers

two_numb <- combn(names(df), 2, simplify = FALSE)

result <- list()

for(i in 1:length(two_numb)) {
 result[[i]] <- df %>%
 mutate(comb = paste0(!!as.symbol(two_numb[[i]][1]), !!as.symbol(two_numb[[i]][2]))) %>%
 select(comb)
}

bind_rows(result) %>%
 group_by(comb) %>%
 tally()

   comb      n
   <chr> <int>
 1 13        2
 2 15        1
 3 16        1
 4 24        2
 5 25        1
 6 26        1
 7 34        1
 8 35        2
 9 36        1
10 45        2
11 46        1

#Three numbers

three_numb <- combn(names(df), 3, simplify = FALSE)

result <- list()

for(i in 1:length(three_numb)) {
 result[[i]] <- df %>%
  mutate(comb = paste0(!!as.symbol(three_numb[[i]][1]), !!as.symbol(three_numb[[i]][2]), 
                       !!as.symbol(three_numb[[i]][3]))) %>%
  select(comb)
}

bind_rows(result) %>%
 group_by(comb) %>%
 tally()

  comb      n
  <chr> <int>
1 135       1
2 136       1
3 245       1
4 246       1
5 345       1