2016-02-28 68 views
0

我正在嘗試使用下面顯示的VarList的函數進行合併。主要思想是該函數返回一個堆棧數據。從R列表中使用循環合併選定的數據R

[[1]] 

Var Number 

1 E 7 

2 F 8 

3 G 6 

[[2]] 

    Var Number 

1 W 3 

2 O 1 

3 I 8 

4 P 5 

5 K 4 


[[3]] 

Var Number 

1 A 1 

回答

1

我們可以使用do.call

do.call(rbind, VarList[c(1,3)]) 

如果我們需要一個函數

stackedFn <- function(lst, index){ 
     list(`row.names<-`(do.call(rbind, lst[index]), NULL)) 

     } 
stackedFn(VarList, c(1,3)) 
#[[1]] 
# Var Number 
#1 E  7 
#2 F  8 
#3 G  6 
#4 A  1 
#5 B  6 
#6 C  3 
#7 D  7 

使用for循環

stackedForFn <- function(lst, index){ 
     res <- NULL 
     for(i in seq_along(index)){ 
     res <- rbind(res, lst[[index[i]]]) 
     } 
     row.names(res) <- NULL 
     list(res) 
     } 

stackedForFn(VarList, c(1,3)) 
#[[1]] 
# Var Number 
#1 E  7 
#2 F  8 
#3 G  6 
#4 A  1 
#5 B  6 
#6 C  3 
#7 D  7 

通過在選擇第二個元素

stackedForFn(VarList, 2) 
#[[1]] 
# Var Number 
#1 W  3 
#2 O  1 
#3 I  8 
#4 P  5 
#5 K  4 

使用一個參數

stackedForFnMod <- function(lst){ 
     res <- NULL 
     for(i in seq_along(lst)){ 
     res <- rbind(res, lst[[i]]) 
     } 
     row.names(res) <- NULL 
     list(res) 
     } 

stackedForFnMod(VarList[c(1,3)]) 
#[[1]] 
# Var Number 
#1 E  7 
#2 F  8 
#3 G  6 
#4 A  1 
#5 B  6 
#6 C  3 
#7 D  7 
+0

@ S.Bine我用'for'循環更新。如果有效,請考慮通過點擊投票旁邊的勾號來接受解決方案。 – akrun

+0

這種方式的效果不錯,但並不完全符合我的要求。我正在尋找通過調用提供相同的輸出功能: stackedForFn(VarList [c(1,3)]) – Binchen

+0

@Binchen我不知道你想要什麼。它給出了與您所展示的完全相同的輸出。 – akrun