1
4

1 回答 1

2

This will do the job:

# first define the function we will apply to each group
f <- function(group) {
    if (nrow(group) == 1 | sum(group$status) == 0) 
        group
    else 
        with(group, {
                v1 = combn(v1, sum(status), sum)
                v2 = combn(v2, sum(status), sum)
                status = ifelse(combn(status, sum(status), sum) == sum(status), 1, 0)
                subject = seq_along(v1)
                group = rep(group, length.out=length(v1))
                data.frame(group, subject, status, v1, v2)
        })
}

# apply f using by and collapse the results into a data.frame
do.call(rbind, by(data, INDICES=data$group, f))

#     group subject status v1 v2
# 1.1     1       1      0 11 31
# 1.2     1       2      1  7 30
# 1.3     1       3      0 10 19
# 2.4     2       1      0 15 93
# 2.5     2       2      0 19 83
# 2.6     2       3      0 16 87
# 2.7     2       4      1 13 19
# 3       3       1      1  9 37
于 2012-10-24T16:46:47.290 回答