multiply multiple column and find sum of each column for multiple values

前端 未结 1 987
渐次进展
渐次进展 2021-01-29 17:07

I\'m trying to multiply column and get its names. I have a data frame:

v1 v2 v3 v4 v5  
 0  1  1  1  1
 0  1  1  0  1
 1  0  1  1  0

I\'m tryin

相关标签:
1条回答
  • 2021-01-29 17:25

    Try this:

    df <- read.table(text = "v1 v2 v3 v4 v5  
     0  1  1  1  1
     0  1  1  0  1
     1  0  1  1  0", skip = 1)
    
    df
    
    ll <- vector(mode = "list", length = ncol(df)-1)
    
    ll <- lapply(2:ncol(df), function(ncols){
      tmp <- t(apply(df, 1, function(rows) combn(x = rows, m = ncols, prod)))
      if(ncols < ncol(df)){
      tmp <- colSums(tmp)
      }
      else{
        tmp <- sum(tmp)
      }
      names1 <- t(combn(x = colnames(df), m = ncols))
      names(tmp) <- apply(names1, 1, function(rows) paste0(rows, collapse = ""))
      ll[[ncols]] <- tmp
    })
    
    ll
    
    # [[1]]
    # V1V2 V1V3 V1V4 V1V5 V2V3 V2V4 V2V5 V3V4 V3V5 V4V5 
    #    0    1    1    0    2    1    2    2    2    1 
    # 
    # [[2]]
    # V1V2V3 V1V2V4 V1V2V5 V1V3V4 V1V3V5 V1V4V5 V2V3V4 V2V3V5 V2V4V5 V3V4V5 
    #      0      0      0      1      0      0      1      2      1      1 
    # 
    # [[3]]
    # V1V2V3V4 V1V2V3V5 V1V2V4V5 V1V3V4V5 V2V3V4V5 
    #        0        0        0        0        1 
    # 
    # [[4]]
    # V1V2V3V4V5 
    #          0
    

    Edit following comment The results of the different set of column combinations can then be accessed by indexing (subsetting) the list. E.g. to access the "2 combinations", select the first element of the list, to access the "3rd combination", select the second element of the list, et c.

    ll[[1]]
    # V1V2 V1V3 V1V4 V1V5 V2V3 V2V4 V2V5 V3V4 V3V5 V4V5 
    #    0    1    1    0    2    1    2    2    2    1
    
    0 讨论(0)
提交回复
热议问题