【问题标题】:Subsets of data frame数据框的子集
【发布时间】:2013-09-01 13:22:11
【问题描述】:

我有一个数据框,其中包含 R 中的条目,并希望从该数据框创建所有可能的唯一子集,此时每个子集应包含原始数据框列池中两列的唯一可能成对组合。这意味着如果原始数据框中的列数是 Y,我应该得到的唯一子集的数量是 Y*(Y-1)/2。我还希望每个子集中列的名称是原始数据框中使用的名称。我该怎么做?

【问题讨论】:

  • 嗨,欢迎来到 SO。由于您是新来的,您可能想阅读网站的aboutFAQ 部分,以帮助您充分利用它。另请阅读how to make a great reproducible example 并相应地更新您的问题!在 OP 未显示他们已经尝试过的内容和/或所需输出的情况下发布的问题往往会被否决或关闭。只是提醒你下次。
  • 对每对列应用什么函数以在新数据框中创建另一列?

标签: r dataframe subset


【解决方案1】:
colpairs <- function(d) {
  apply(combn(ncol(d),2), 2, function(x) d[,x])
}

x <- colpairs(iris)
sapply(x, head, n=2)

## [[1]]
##   Sepal.Length Sepal.Width
## 1          5.1         3.5
## 2          4.9         3.0
## 
## [[2]]
##   Sepal.Length Petal.Length
## 1          5.1          1.4
## 2          4.9          1.4
...

【讨论】:

    【解决方案2】:

    我会使用combn 来制作列的索引,并使用lapply 来获取data.frame 的子集并将它们存储在list 结构中。例如

    #  Example data
    set.seed(1)
    df <- data.frame( a = sample(2,4,repl=T) ,
                b = runif(4) ,
                c = sample(letters ,4 ),
                d = sample( LETTERS , 4 ) )
    
    # Use combn to get indices
    ind <- combn( x = 1:ncol(df) , m = 2  , simplify = FALSE )
    
    #  ind is the column indices. The indices returned by the example above are (pairs in columns):     
    #[,1] [,2] [,3] [,4] [,5] [,6]
    #[1,]    1    1    1    2    2    3
    #[2,]    2    3    4    3    4    4
    
    #  Make subsets, combine in list
    out <- lapply( ind , function(x) df[,x] )
    [[1]]
    #  a         b
    #1 1 0.2016819
    #2 1 0.8983897
    #3 2 0.9446753
    #4 2 0.6607978
    
    [[2]]
    #  a c
    #1 1 q
    #2 1 b
    #3 2 e
    #4 2 x
    
    [[3]]
    #  a d
    #1 1 R
    #2 1 J
    #3 2 S
    #4 2 L
    
    [[4]]
    #          b c
    #1 0.2016819 q
    #2 0.8983897 b
    #3 0.9446753 e
    #4 0.6607978 x
    
    [[5]]
    #          b d
    #1 0.2016819 R
    #2 0.8983897 J
    #3 0.9446753 S
    #4 0.6607978 L
    
    [[6]]
    #  c d
    #1 q R
    #2 b J
    #3 e S
    #4 x L
    

    【讨论】:

    • 你不需要lapplycombn( x = 1:ncol(df) , m = 2 , FUN=function(x) df[,x], simplify = FALSE )
    • @Roland 谢谢,我总是忘记你可以向combn 提供函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-04
    • 2017-12-25
    • 2022-10-20
    • 2018-11-30
    相关资源
    最近更新 更多