Unique combination of columns

邮差的信 提交于 2019-12-22 09:25:07

问题


here is my simplified data set:

foo <- data.frame(var1= c(1:10), var2=rep(1:5,2),var3=rep(1:2,5),var4=rep(3:7,2) )    

all together 20 variables

foo

   var1 var2 var3   var4    ... var20
1     1    1    1      3
2     2    2    2      4
3     3    3    1      5
4     4    4    2      6
5     5    5    1      7
6     6    1    2      3
7     7    2    1      4
8     8    3    2      5
9     9    4    1      6
10   10    5    2      7

I need to get a unique combination of 3 variables and its sum for each period

ie. sth like

  var1var2var3   var1var3var4   var1var5var18  etc...
1     6               sum
2     6           
3     7          
4     10           
5     11           
6     9         
7     10             
8     13          
9     14          
10    17         

note that var1var3var5 is the same as var3var1var5


回答1:


As @Chase suggested, combn gets you what you want:

nams <- apply( combn(colnames(foo),3), 2, function(z) paste(z, collapse = ''))
cols <- combn( ncol(foo), 3)

tripleSums <- apply( cols, 2, function(z) rowSums(foo[,z]))
colnames(tripleSums) <- nams

> tripleSums
      var1var2var3 var1var2var4 var1var3var4 var2var3var4
 [1,]            3            5            5            5
 [2,]            6            8            8            8
 [3,]            7           11            9            9
 [4,]           10           14           12           12
 [5,]           11           17           13           13
 [6,]            9           10           11            6
 [7,]           10           13           12            7
 [8,]           13           16           15           10
 [9,]           14           19           16           11
[10,]           17           22           19           14


来源:https://stackoverflow.com/questions/5081311/unique-combination-of-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!