【发布时间】:2019-03-29 22:38:49
【问题描述】:
我需要扩展一些数据,然后通过tail限制哪些数据保留。
数据示例:
list_1 <- list(1:15)
list_2 <- list(16:30)
list_3 <- list(31:45)
short_lists[[1]] <- list_1
short_lists[[2]] <- list_2
short_lists[[3]] <- list_3
str(short_lists)
List of 3
$ :List of 1
..$ : int [1:15] 1 2 3 4 5 6 7 8 9 10 ...
$ :List of 1
..$ : int [1:15] 16 17 18 19 20 21 22 23 24 25 ...
$ :List of 1
..$ : int [1:15] 31 32 33 34 35 36 37 38 39 40 ...
以及我希望给定列表的尾部来自 list_1、list_2、list_3 多长时间
how_long <-
c(4,2,5,3,6,4,7,5,8,6,9,7,10,8,2,4,6,8,10,12,14,10,9,7,11)
我通过嵌套的 for 循环进行扩展并尝试获取扩展列表的尾部,但只获取扩展列表。
for (i in 1:length(how_long)) {
for (j in 1:length(short_lists)) {
tail_temp[[j]][i] <- tail(short_lists2[[j]], n = how_long[i])
}
}
这会产生:
str(tail_temp)
List of 3
$ :List of 25
..$ : int [1:15] 1 2 3 4 5 6 7 8 9 10 ...
..$ : int [1:15] 1 2 3 4 5 6 7 8 9 10 ...
..$ : int [1:15] 1 2 3 4 5 6 7 8 9 10 ...
[snip]
..$ : int [1:15] 1 2 3 4 5 6 7 8 9 10 ...
$ :List of 25
..$ : int [1:15] 16 17 18 19 20 21 22 23 24 25 ...
..$ : int [1:15] 16 17 18 19 20 21 22 23 24 25 ...
..$ : int [1:15] 16 17 18 19 20 21 22 23 24 25 ...
[snip]
..$ : int [1:15] 16 17 18 19 20 21 22 23 24 25 ...
$ :List of 25
..$ : int [1:15] 31 32 33 34 35 36 37 38 39 40 ...
..$ : int [1:15] 31 32 33 34 35 36 37 38 39 40 ...
..$ : int [1:15] 31 32 33 34 35 36 37 38 39 40 ...
[snip]
..$ : int [1:15] 31 32 33 34 35 36 37 38 39 40 ...
我很高兴 j 的扩展,但我从来没有得到尾声和我正在寻找的东西:
str(tail_temp)
List of 3
$ :List of 25
..$ : int [1:4] 12 13 14 15
..$ : int [1:2] 14 15
..$ : int [1:5] 11 12 13 14 15
[snip]
所以我错过了什么简单的事情。任何帮助表示赞赏。谢谢。
【问题讨论】:
标签: r nested-loops