Home > Software engineering >  create a vector with maximum of two vectors for last five elements
create a vector with maximum of two vectors for last five elements

Time:11-26

I have two vectors

a <- c(1,1,1,1,20,30,40,100,300)
b <- c(2,2,2,2,100,0,0,120,5)

I want to create a vector that compares and gives you the maximum of both vectors only for last 5 elements.

The first 4 elements must remain the same as in vector a.

output <- c(1,1,1,1,100,30,40,120,300)

CodePudding user response:

Use pmax. You're using vectors, not lists.

> pmax(a,b)
[1] 100  30  40 120 300

Using your updated vectors:

> a <- c(1,1,1,1,20, 30,40,100,300)
> b <- c(2,2,2,2, 100, 0, 0, 120, 5)
> c(a[!a %in% tail(a, 5)], pmax(tail(a, 5), tail(b, 5)))
[1]   1   1   1   1 100  30  40 120 300

CodePudding user response:

``` r
a <- c(1,1,1,1,20,30,40,100,300)
b <- c(2,2,2,2,100,0,0,120,5)

replace(a, tail(seq(a),5), pmax(tail(a,5),tail(b,5)))
#> [1]   1   1   1   1 100  30  40 120 300

CodePudding user response:

We can do it this way using head and tail:

c(head(a,-5), ifelse(tail(a,5)>tail(b,5), tail(a,5), tail(b,5)))
[1]   1   1   1   1 100  30  40 120 300
  •  Tags:  
  • r
  • Related