R 在位置分割数字向量 [英] R split numeric vector at position

查看:72
本文介绍了R 在位置分割数字向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在某个索引处将向量分成两个的简单任务:

I am wondering about the simple task of splitting a vector into two at a certain index:

splitAt <- function(x, pos){
  list(x[1:pos-1], x[pos:length(x)])
}

a <- c(1, 2, 2, 3)

> splitAt(a, 4)
[[1]]
[1] 1 2 2

[[2]]
[1] 3

我的问题:一定有一些现有的功能,但我找不到它?也许 split 有可能吗?如果 pos=0pos>length(a),我的幼稚实现也不起作用.

My question: There must be some existing function for this, but I can't find it? Is maybe split a possibility? My naive implementation also does not work if pos=0 or pos>length(a).

推荐答案

一个改进是:

splitAt <- function(x, pos) unname(split(x, cumsum(seq_along(x) %in% pos)))

现在可以采用位置向量:

which can now take a vector of positions:

splitAt(a, c(2, 4))
# [[1]]
# [1] 1
# 
# [[2]]
# [1] 2 2
# 
# [[3]]
# [1] 3

如果 pos <= 0pos >= length(x) 在某种意义上,它确实表现正确(主观)它在单个列表项中返回整个原始向量.如果您希望它出错,请在函数顶部使用 stopifnot.

And it does behave properly (subjective) if pos <= 0 or pos >= length(x) in the sense that it returns the whole original vector in a single list item. If you'd like it to error out instead, use stopifnot at the top of the function.

这篇关于R 在位置分割数字向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆