R使用嵌套for循环尾部扩展和处理数据

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

我需要扩展一些数据,然后通过尾部限制哪些数据。

数据示例:

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
1个回答
0
投票

非常接近。

我更喜欢R中列表中的矢量。 如果你熟悉python,矢量的行为就像python中的'lists'。 R中的列表就像词典一样。

因此,您只需要首先取消列表(转换为向量), 然后分配给列表的项目,因此它应分配给: tail_temp[[i]][[j]]而不是tail_temp[i][[j]]

list_1 <- list(1:15)
list_2 <- list(16:30)
list_3 <- list(31:45)
short_lists = list()
short_lists[[1]] <- list_1
short_lists[[2]] <- list_2
short_lists[[3]] <- 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)

tail_temp = list()

for (i in 1:length(short_lists)){
    tail_temp[[i]] = list()
    for (j in 1:length(how_long)){
       tail_temp[[i]][[j]] <- tail(unlist(short_lists[[i]]), n = how_long[j])
    }
}

产量

[[1]]
[[1]][[1]]
[1] 12 13 14 15

[[1]][[2]]
[1] 14 15

[[1]][[3]]
[1] 11 12 13 14 15
…
[[3]][[23]]
[1] 37 38 39 40 41 42 43 44 45

[[3]][[24]]
[1] 39 40 41 42 43 44 45

[[3]][[25]]
 [1] 35 36 37 38 39 40 41 42 43 44 45
© www.soinside.com 2019 - 2024. All rights reserved.