使用R中的循环组合列表中的选定数据(Combine Selected Data from a List Using a Loop in R)

编程入门 行业动态 更新时间:2024-10-26 08:29:39
使用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 1

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

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

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

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

更多推荐

本文发布于:2023-07-16 03:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1123436.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   数据   列表中   Combine   Loop

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!