简体   繁体   English

从R中的列表中提取元素序列

[英]Extract sequence of elements from a list in R

I am looking for a shorter expression for something like the following: 我正在寻找类似以下内容的简短表达:

list(x[[1]],x[[2]],x[[3]],x[[4]])

I tried 我试过了

list(x[[1:4]])

and

list(x[1:4])

but none of these do what the original expression does. 但是这些都不像原始表达式那样。

The simple approach is just: 简单的方法是:

x[[1:4]]

no need to wrap it in list . 无需将其包装在list

If you need to do something a little more complicated, then lapply can be used as well (overkill for this, but I will show an example anyways in case it helps for other cases): 如果您需要做一些更复杂的事情,那么也可以使用lapply (对此有点过头了,但是无论如何我都会显示一个示例,以防其他情况):

> x <- list()
> x[[1]] <- lm(Sepal.Length ~ ., data=iris)
> x[[2]] <- lm(Sepal.Width ~ ., data=iris)
> x[[3]] <- lm(Petal.Width ~ ., data=iris)
> x[[4]] <- lm(Petal.Length ~ ., data=iris)
> x[[5]] <- lm(Petal.Length ~ Petal.Width, data=iris)
> 
> test1 <- list(x[[1]], x[[2]], x[[3]], x[[4]])
> test2 <- x[1:4]
> test3 <- lapply(1:4, function(i) x[[i]])
> 
> identical(test1,test2)
[1] TRUE
> identical(test1,test3)
[1] TRUE
> 

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

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