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

问题描述 投票:0回答:1

我正在寻找一个更短的表达式,如下所示:

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

我试过了

list(x[[1:4]])

list(x[1:4])

但这些都不是原始表达式所做的。

r
1个回答
3
投票

简单的方法就是:

x[[1:4]]

无需将其包裹在list中。

如果你需要做一些更复杂的事情,那么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
> 
© www.soinside.com 2019 - 2024. All rights reserved.