Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a vector by delimiter?

Tags:

r

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?

like image 526
chyx Avatar asked Dec 13 '12 10:12

chyx


People also ask

How do you split a vector in C++?

Split a vector into sub-vectors of size n in C++We start by determining the total number of sub-vectors of size n formed from the input vector. Then we iterate the given vector, and in each iteration of the loop, we process the next set of n elements and copy it to a new vector using the std::copy algorithm.

How do you split from delimiter?

You can use the split() method of String class from JDK to split a String based on a delimiter e.g. splitting a comma-separated String on a comma, breaking a pipe-delimited String on a pipe, or splitting a pipe-delimited String on a pipe.

How do you split a character vector in R?

Note that splitting into single characters can be done via split = character(0) or split = "" ; the two are equivalent.


1 Answers

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
like image 195
flodel Avatar answered Sep 23 '22 11:09

flodel