Home > Enterprise >  Remove the last 0 in a list of vectors if it appears twice at the end
Remove the last 0 in a list of vectors if it appears twice at the end

Time:07-01

I have data as follows:

dat <- list(`A` = c(0, 25, 500, 1000, 0, 0), `B` = c(0, 
25, 500, 1000, 1500, 0)

I would like to remove the last 0 if there are two 0's.

I am breaking my brain on how to achieve this but I cannot come up with anything.

How should I do this?

Desired output:

out_dat <- list(`A` = c(0, 25, 500, 1000, 0), `B` = c(0, 
25, 500, 1000, 1500, 0)

CodePudding user response:

One solution:

trim0 <- function (x) {
  if (all(tail(x, 2) == 0)) x[-length(x)] else x
}

out_dat <- lapply(dat, trim0)

CodePudding user response:

You can use the following code:

lapply(dat, function(x) x[c(TRUE, !x[-length(x)] == x[-1])])

Output:

$A
[1]    0   25  500 1000    0

$B
[1]    0   25  500 1000 1500    0

CodePudding user response:

Try this

lapply(dat , \(x) if(rev(x)[1] == rev(x)[2] & rev(x)[1] == 0) x[1:(length(x) - 1)] else x)
  • output
$A
[1]    0   25  500 1000    0

$B
[1]    0   25  500 1000 1500    0
  • Related