[英]Extract sequence of elements from a list in R
我正在尋找類似以下內容的簡短表達:
list(x[[1]],x[[2]],x[[3]],x[[4]])
我試過了
list(x[[1:4]])
和
list(x[1:4])
但是這些都不像原始表達式那樣。
簡單的方法是:
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
>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.