Capturing the last element of a vector

I have a pretty simple problem that brings me sadness despite a couple of hours of hair hanging, so I thought I would ask for your help. I am looking for a simple way to return a vector containing only the last element of some source vector.

This is my original vector, 'a':

a<-c(0,0,1,0,0,1,0,0,1,0) 

I want to create a vector "b" that has the same length as "a" and carries only the last element, which does not make sense. In other words,

 b = (0,0,0,0,0,0,0,0,1,0) 

I was able to do this by constructing a loop going back from the end of the 'a' vector to its first element, but this seems clearly inelegant. I am sure there is a better way.

In case someone is interested, a more serious problem: I try to change the value of one vector, where it corresponds to the last non-empty element of another vector.

Thanks so much for any help.

+6
source share
5 answers

One of the options:

 b<- numeric(length(a)) b[max(which(a!=0))] <- 1 b #[1] 0 0 0 0 0 0 0 0 1 0 
+5
source

This is just for fun as a single line:

 `[<-`(a, rev(which(as.logical(a)))[-1], 0) ## [1] 0 0 0 0 0 0 0 0 1 0 

And a slightly different version:

 `[<-`(integer(length = length(a)), rev(which(a != 0))[1], 1) ## [1] 0 0 0 0 0 0 0 0 1 0 
+7
source

I believe this should work too

 ifelse(cumsum(a)==sum(a), a, 0) # [1] 0 0 0 0 0 0 0 0 1 0 

This assumes that the “missing” values ​​are zeros, and the values ​​without gaps are 1. If you have values ​​other than 1, you would do

 ifelse(cumsum(a!=0)==sum(a!=0), a, 0) 
+6
source

I'm a little late, but here is another option:

 a[head(which(a == 1), -1)] <- 0 

or

 replace(a, head(which(a == 1), -1), 0) 

Benchmarks

 Unit: milliseconds expr min lq median uq max neval akrun() 8.600 9.201 11.346 12.531 68.45 100 plourde() 9.034 9.767 11.545 12.498 69.33 100 flick() 164.792 215.759 221.868 227.237 333.72 100 thomas() 4.210 6.427 8.108 9.913 66.65 100 

Functions

 akrun <- function() { b<- numeric(length(a)) b[max(which(a!=0))] <- 1 b } plourde <- function() replace(a, head(which(a == 1), -1), 0) flick <- function() ifelse(cumsum(a)==sum(a), a, 0) thomas <- function() `[<-`(a, rev(which(as.logical(a)))[-1], 0) 
+4
source

Another simple option:

 n = max(which(as.logical(a))) - 1 c(numeric(n), tail(a, -n)) 
+3
source

Source: https://habr.com/ru/post/984025/


All Articles