如何编写将数据帧转换为另一个数据帧的函数?

How to write a function that transform a dataframe to another dataframe?

假设我有一个如下形式的数据框:

    N1  N2  N3  N4  N5  N6
     1   0   0   1   0   0
     0   1   0   1   0   1
     1   1   1   0   0   1
     0   0   0   1   1   0
     1   1   0   0   0   1

我想编写一个函数,将上述数据框转换为这样的意外事件 table:

            (N2=0,N3=0) (N2=0,N3=1) (N2=1,N3=0) (N2=1,N3=1)      
     N5=0       1            0           2           0
     N5=1       1            0           0           1

我可以在其中指定构成列和行的变量。如果可能的话,一个函数,我也可以在其中替换不同的数据框。谢谢!

假设 df 是您的数据框:

with(df, t(table(paste0(N2, N3), N5)))
N5  00 10 11
  0  1  2  1
  1  1  0  0

也许不是一个完美的解决方案,但考虑这个功能:

f <- function(df, select) {

    generate.levels <- function(...) {
        x <- do.call(expand.grid, rev(list(...)))
        if (ncol(x) > 1) x <- x[,ncol(x):1]
        for (i in 1:ncol(x)) x[,i] <- sprintf("%s=%s", names(x)[i], x[,i])
        x <- apply(x, 1, paste, collapse=",")
        x <- paste0("(", x, ")")
        x
    }

    x <- subset(df, select=select)
    l <- do.call(generate.levels, lapply(x, unique))
    for (i in 1:ncol(x)) x[,i] <- sprintf("%s=%s", names(x)[i], x[,i])
    x <- apply(x, 1, paste, collapse=",")
    x <- paste0("(", x, ")")
    factor(x, levels=l)
}

table(f(df, "N5"), f(df, c("N2", "N3")))

       (N2=0,N3=0) (N2=0,N3=1) (N2=1,N3=0) (N2=1,N3=1)
(N5=0)           1           0           2           1
(N5=1)           1           0           0           0