Cut out a vector in several vectors

2

Be the following vector:

x <- c(1, 2, "a", 2, 3, 4, "a", 3)

I need to cut a vector in multiple vectors contained in a list, starting from an element of the same vector, in this case from "a" :

[[1]]
[1] 1 2

[[2]]
[1] 2 3 4

[[3]]
[1] 3

Any suggestions?

    
asked by Marco Uscuchagua 11.09.2018 в 01:18
source

2 answers

1

With R base you could do the following:

x <- c(1, 2, 9, 2, 3, 4, 9, 3)

nro_split <- 9
lapply(split(x, cumsum(x == nro_split)), function(x) {x[x!=nro_split]})


$'0'
[1] 1 2

$'1'
[1] 2 3 4

$'2'
[1] 3

In this example we want to cut in blocks starting from the appearance of a 9 .

  • First of all cumsum(x == nro_split) will arm the groups from each occurrence of nro_split , that is: [1] 0 0 1 1 1 1 2 2
  • Applying then split() we separate each block in a list
  • The only thing that we would have to do is eliminate every nro_split , for that we apply with lapply function function(x) {x[x!=nro_split]} .
answered by 11.09.2018 / 02:20
source
2

the split function is what you need. You have to give him a factor so he knows how to group, for example:

split(c(1,2,3,4),c(1,2,2,1))

returns a list with 1 and 4 in the first entry and then 2 and 3.

For your problem cumsum(x=="a") creates the factor that is needed.

Then you have to make sure you delete the "a" so that they are not included in the list, and once deleted, you should convert to integers with as.integer:

split(as.integer(x[x!="a"]),cumsum(x=="a")[x!="a"])
    
answered by 11.09.2018 в 02:38