使用R中的循环组合列表中的选定数据(Combine Selected Data from a List Using a Loop in R)
我正在尝试使用下面显示的VarList函数进行整合。 主要思想是功能是返回堆叠数据。
[[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 1I am trying to consolidate using a function for VarList shown below. 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最满意答案
我们可以使用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通过选择list的第二个元素
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 7We can use 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 7Using a for loop
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 7By selecting the 2nd element in the list
stackedForFn(VarList, 2) #[[1]] # Var Number #1 W 3 #2 O 1 #3 I 8 #4 P 5 #5 K 4Using 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更多推荐
发布评论