我必须在r中把一个向量分成n个相等大小的块,我找不到任何基函数来做这个。谷歌也没帮上什么忙。这是我目前想到的;
x <- 1:10
n <- 3
chunk <- function(x,n) split(x, factor(sort(rank(x)%%n)))
chunk(x,n)
$`0`
[1] 1 2 3
$`1`
[1] 4 5 6 7
$`2`
[1] 8 9 10
我必须在r中把一个向量分成n个相等大小的块,我找不到任何基函数来做这个。谷歌也没帮上什么忙。这是我目前想到的;
x <- 1:10
n <- 3
chunk <- function(x,n) split(x, factor(sort(rank(x)%%n)))
chunk(x,n)
$`0`
[1] 1 2 3
$`1`
[1] 4 5 6 7
$`2`
[1] 8 9 10
当前回答
还有一种可能是package parallel中的splitIndices函数:
library(parallel)
splitIndices(20, 3)
给:
[[1]]
[1] 1 2 3 4 5 6 7
[[2]]
[1] 8 9 10 11 12 13
[[3]]
[1] 14 15 16 17 18 19 20
注意:这只适用于数值。如果你想拆分一个字符向量,你需要做一些索引:lapply(splitIndices(20,3), \(x) letters[1:20][x])
其他回答
chunk2 <- function(x,n) split(x, cut(seq_along(x), n, labels = FALSE))
我需要一个接受数据参数的函数。Table(引号中)和另一个参数,该参数是原始data.table的子集中行数的上限。这个函数产生任意数量的数据。表的上限允许:
library(data.table)
split_dt <- function(x,y)
{
for(i in seq(from=1,to=nrow(get(x)),by=y))
{df_ <<- get(x)[i:(i + y)];
assign(paste0("df_",i),df_,inherits=TRUE)}
rm(df_,inherits=TRUE)
}
这个函数给出了一系列数据。命名为df_[number]的表,其起始行来自原始数据。表中的名称。最后一个数据。表可以很短,并且填满了NAs,所以你必须将其子集返回到任何剩下的数据。这种类型的函数很有用,因为某些GIS软件对您可以导入的地址引脚数量有限制。切片数据。不建议将表分成更小的块,但这可能是不可避免的。
将d分成大小为20的块的一行代码:
split(d, ceiling(seq_along(d)/20))
更多细节:我认为你只需要seq_along(), split()和ceiling():
> d <- rpois(73,5)
> d
[1] 3 1 11 4 1 2 3 2 4 10 10 2 7 4 6 6 2 1 1 2 3 8 3 10 7 4
[27] 3 4 4 1 1 7 2 4 6 0 5 7 4 6 8 4 7 12 4 6 8 4 2 7 6 5
[53] 4 5 4 5 5 8 7 7 7 6 2 4 3 3 8 11 6 6 1 8 4
> max <- 20
> x <- seq_along(d)
> d1 <- split(d, ceiling(x/max))
> d1
$`1`
[1] 3 1 11 4 1 2 3 2 4 10 10 2 7 4 6 6 2 1 1 2
$`2`
[1] 3 8 3 10 7 4 3 4 4 1 1 7 2 4 6 0 5 7 4 6
$`3`
[1] 8 4 7 12 4 6 8 4 2 7 6 5 4 5 4 5 5 8 7 7
$`4`
[1] 7 6 2 4 3 3 8 11 6 6 1 8 4
还有一种可能是package parallel中的splitIndices函数:
library(parallel)
splitIndices(20, 3)
给:
[[1]]
[1] 1 2 3 4 5 6 7
[[2]]
[1] 8 9 10 11 12 13
[[3]]
[1] 14 15 16 17 18 19 20
注意:这只适用于数值。如果你想拆分一个字符向量,你需要做一些索引:lapply(splitIndices(20,3), \(x) letters[1:20][x])
如果这个答案来得这么晚,我很抱歉,但也许它对其他人有用。实际上,这个问题有一个非常有用的解决方案,在?split的末尾解释了。
> testVector <- c(1:10) #I want to divide it into 5 parts
> VectorList <- split(testVector, 1:5)
> VectorList
$`1`
[1] 1 6
$`2`
[1] 2 7
$`3`
[1] 3 8
$`4`
[1] 4 9
$`5`
[1] 5 10