【问题标题】:How to write a function that transform a dataframe to another dataframe?如何编写将数据帧转换为另一个数据帧的函数?
【发布时间】:2016-12-04 09:55:56
【问题描述】:

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

    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

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

【问题讨论】:

    标签: r dataframe contingency


    【解决方案1】:

    假设 df 是您的数据框:

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

    【讨论】:

    • 不是一个很好的答案(尽管 OP 喜欢它),因为没有 (N2=0,N3=1) 的列。
    【解决方案2】:

    也许不是一个完美的解决方案,但考虑一下这个函数:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多