簡體   English   中英

如何在R中的第10個項目處拆分列表?

[英]How to split list at every 10th item in R?

我有100件物品的清單。 我想在代碼1中的每個第十個項目之后將其拆分。代碼2是關於兩個以前的列表的列表,並將其拆分為每個包含10個項目的20個列表。

代碼1

預期輸出:10個清單,共10個項目。

A <- 100
a <- rnorm(A) # [1:100]
n <- 10
str(a)

# Not resulting in equal size of chunks with vectors so reject
# http://stackoverflow.com/a/3321659/54964
#d <- split(d, ceiling(seq_along(d)/(length(d)/n)))

# Works for vectors but not with lists
# http://stackoverflow.com/a/16275428/54964
#d <- function(d,n) split(d, cut(seq_along(d), n, labels = FALSE)) 

str(d)

測試代碼2

輸入:兩個清單的清單

aa <- list(a, rnorm(a))

預期輸出:10個項目大小的20個列表

測試Loki的答案

segmentLists <- function(A, segmentSize) {
  res <- lapply(A, function(x) split(unlist(x), cut(seq_along(unlist(x)), segmentSize, labels = F)))

  #print(res)    
  res <- unlist(res, recursive = F)
}

segmentLists(aa, 10)

輸出:循環正在進行,永不停止

操作系統:Debian 8.5
R:3.3.1

您可以使用lapply

aa <- list(a, rnorm(a))
aa
n <- 10

x <- lapply(aa, function(x) split(unlist(x), cut(seq_along(unlist(x)), n, labels = F)))
y <- unlist(x, recursive = F)
str(y)
# List of 20
# $ 1 : num [1:10] 1.0895 -0.0477 0.225 -0.6308 -0.1558 ...
# $ 2 : num [1:10] -0.469 -0.381 0.709 -0.798 1.183 ...
# $ 3 : num [1:10] 0.757 -1.128 -1.394 -0.712 0.494 ...
# $ 4 : num [1:10] 1.135 0.324 0.75 -0.83 0.794 ...
# $ 5 : num [1:10] -0.786 -0.068 -0.179 0.354 -0.597 ...
# $ 6 : num [1:10] -0.115 0.164 -0.365 -1.827 -2.036 ...
...

length(y)
# [1] 20

要刪除y中的列表元素的名稱( $ 1$ 2等),可以使用unname()

str(unname(y))
# List of 20
# $ : num [1:10] 1.0895 -0.0477 0.225 -0.6308 -0.1558 ...
# $ : num [1:10] -0.469 -0.381 0.709 -0.798 1.183 ...
# $ : num [1:10] 0.757 -1.128 -1.394 -0.712 0.494 ...
# $ : num [1:10] 1.135 0.324 0.75 -0.83 0.794 ...
# $ : num [1:10] -0.786 -0.068 -0.179 0.354 -0.597 ...
...

使用函數,您必須在函數末尾返回res

segmentLists <- function(A, segmentSize)
{
  res <- lapply(A, function(x) split(unlist(x), cut(seq_along(unlist(x)), segmentSize, labels = F)))

  #print(res)

  res <- unlist(res, recursive = F)
  res <- unname(res)
  res
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM