在R中创建穷举案例列

时间:2018-08-20 09:05:10

标签: r combinations permutation generate

我正在尝试生成一列“性别组合”,以创建互动条件的详尽类别,如下表所示。在R中有简单的方法吗?

+--------------+--------------+--------------+---------------------+
| EMP 1 Gender | EMP 2 Gender | Emp 3 Gender | Gender Combinations |
+--------------+--------------+--------------+---------------------+
| Male         |              |              | 1 Male              |
| Female       |              |              | 1 Female            |
|              | Male         |              | 1 Male              |
|              | Female       |              | 1 Female            |
|              |              | Male         | 1 Male              |
|              |              | Female       | 1 Female            |
| Male         | Female       |              | 1 Male, 1 Female    |
|              | Male         | Female       | 1 Male, 1 Female    |
| Male         |              | Female       | 1 Male, 1 Female    |
|              | Female       | Male         | 1 Male, 1 Female    |
| Female       |              | Male         | 1 Male, 1 Female    |
| Female       | Male         |              | 1 Male, 1 Female    |
|              | Female       | Male         | 1 Male, 1 Female    |
| Male         |              | Female       | 1 Male, 1 Female    |
|              | Male         | Female       | 1 Male, 1 Female    |
| Male         | Male         | Female       | 1 Male, 1 Female    |
| Male         | Female       | Male         | 2 Males, 1 Female   |
| Female       | Male         | Male         | 1 Female, 2 Males   |
| Female       | Female       | Male         | 2 Females, 1 Male   |
| Female       | Male         | Female       | 2 Females, 1 Male   |
| Male         | Female       | Female       | 2 Females, 1 Male   |
| Male         | Male         | Male         | 3 Males             |
| Female       | Female       | Female       | 3 Females           |
+--------------+--------------+--------------+---------------------+

1 个答案:

答案 0 :(得分:2)

这是一种使用apply方法并以页边距1捕获行的方法,

dd <- data.frame(V1 = c('M', 'F', '', 'M'), 
                 V2 = c('', 'F', 'M', 'M'), 
                 V3 = c('F', 'M', 'M', ''), stringsAsFactors = FALSE)

dd
#   V1 V2 V3
#1  M     F
#2  F  F  M
#3     M  M
#4  M  M   

apply(dd, 1, function(i){M1 <- sum(i == 'M'); F1 <- sum(i == 'F'); paste0(M1, ' Male', ' ', F1, ' Female')})
#[1] "1 Male 1 Female" "1 Male 2 Female" "2 Male 0 Female" "2 Male 0 Female" 

矢量化解决方案

为避免可怕的apply(df, 1, ...),您可以使用rowSums,即

paste0(rowSums(dd == 'M'), ' Males', ' ', rowSums(dd == 'F'), ' Females')