Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

r - How to split a vector by delimiter?

I have a vector of integer e.g. c(1,2,0,3,4) and I want 0 to be a delimiter and get list(c(1,2), c(3,4)). Is there any libary function I can use?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No library function I know of but you can write your own:

split.vec <- function(vec, sep = 0) {
    is.sep <- vec == sep
    split(vec[!is.sep], cumsum(is.sep)[!is.sep])
}

split.vec(c(1,2,0,3,4), 0)
# $`0`
# [1] 1 2
# 
# $`1`
# [1] 3 4

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...