2016-03-17 97 views
3

我需要有關如何以迭代方式管理列表的幫助。將函數應用於R中的數據框列表

我有以下列表list它由幾個相同的列,但行數不同的數據幀組成。示例:

[[1]] 
    id InpatientDays ERVisits OfficeVisits Narcotics 
1 a    0  0   18   1 
2 b    1  1   6   1 
3 c    0  0   5   3 
4 d    0  1   19   0 
5 e    8  2   19   3 
6 f    2  0   9   2 

[[2]] 
    id InpatientDays ERVisits OfficeVisits Narcotics 
7 a   16  1   8   1 
8 b    2  0   8   0 
9 c    2  1   4   3 
10 d    4  2   0   2 
11 e    6  5   20   2 
12 a    0  0   7   4 

我想應用一個函數來獲取列表中每個「數據框」的id的所有可能組合。

我打算嘗試這樣的事情lapply(list1, function(x) combn(unique(list1[x]$id)))這當然不行..期待得到的東西,如:

[[1]] 
    [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] 
[1,] "a" "a" "a" "a" "a" "b" "b" "b" "b" "c" "c" "c" "d" "d" "e" 
[2,] "b" "c" "d" "e" "f" "c" "d" "e" "f" "d" "e" "f" "e" "f" "f" 

[[2]] 
    [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] 
[1,] "a" "a" "a" "a" "b" "b" "b" "c" "c" "d" 
[2,] "b" "c" "d" "e" "c" "d" "e" "d" "e" "e" 

這可能嗎?我肯定知道這個工程的一個數據幀df

combn(unique(df$id),2) 
+1

不知你已經注意到您的[近期](http://stackoverflow.com/posts/36066336/revisions)[問題](http://stackoverflow.com/posts/36048558/revisions)的重複某種模式...也許[this ](http://stackoverflow.com/tags/dataframes/info)有點幫助? –

回答

6

我們需要使用unique(x$id)

lapply(list1, function(x) combn(unique(x$id),2)) 

的OP的代碼是循環使用的lapply「列表1」。匿名函數調用(function(x))返回list中的每個'data.frame',即'x'是'data.frame'。所以,我們只需要撥打x$id(或x[['id']])來提取'id'列。實質上,'x'不是一個索引。但是,如果我們需要根據索引集,我們通過「列表1」的序列,具有循環(或者如果list元素命名,然後通過它的names循環)

lapply(seq_along(list1), function(i) combn(unique(list1[[i]]$id), 2)) 
相關問題