简体   繁体   English

使用R中的循环组合从列表中选择的数据

[英]Combine Selected Data from a List Using a Loop in R

I am trying to consolidate using a function for VarList shown below. 我正在尝试使用下面显示的VarList函数进行合并。 The main idea is for the function is to return a stacked data. 该函数的主要思想是返回堆叠的数据。

[[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

We can use do.call 我们可以使用do.call

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

If we need a function 如果我们需要一个功能

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

Using a for loop 使用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

By selecting the 2nd element in the list 通过选择list的第二个元素

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

Using a single argument 使用单个参数

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM