2016-07-29 200 views
2

假设我有以下形式的数据帧:如何编写将数据帧转换为另一个数据帧的函数?

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 

我想编写变换上述数据帧到一个列联表这样的功能:

  (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 

在那里我可以指定构成列和行的变量。如果可能的话,我可以用一个函数替换不同的数据帧。谢谢!

回答

4

假设df是您的数据框:

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

辉煌!干杯! – mackbox

+0

不是一个很好的答案(尽管OP喜欢它),因为'(N2 = 0,N3 = 1)'没有列。 – mrbrich

1

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

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 
相关问题