apply a function over groups of columns

后端 未结 6 844
梦谈多话
梦谈多话 2020-11-28 12:18

How can I use apply or a related function to create a new data frame that contains the results of the row averages of each pair of columns in a very large data

6条回答
  •  被撕碎了的回忆
    2020-11-28 12:54

    There is a beautifully simple solution if you are interested in applying a function to each unique combination of columns, in what known as combinatorics.

    combinations <- combn(colnames(df),2,function(x) rowMeans(df[x]))
    

    To calculate statistics for every unique combination of three columns, etc., just change the 2 to a 3. The operation is vectorized and thus faster than loops, such as the apply family functions used above. If the order of the columns matters, then you instead need a permutation algorithm designed to reproduce ordered sets: combinat::permn

提交回复
热议问题