2016-07-29 192 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 
相關問題