-2

I have a tibble where all values are either 0, 1 or -1. I need to locate the last 0 element in each column and replace it with 2. I am trying not to use loop here…

Help!

m45ha
  • 399
  • 1
  • 9

2 Answers2

2

You can create a function that performs the replacement and apply it

library(tidyverse)
set.seed(1234)

df <- tibble(x = sample(-1:1, 4, replace = TRUE),
             y = sample(-1:1, 4, replace = TRUE),
             z = sample(-1:1, 4, replace = TRUE))

replace_last_0 <- function(x) {
  x[tail(which(x == 0), 1)] <- 2
  x
}

# all at once
mutate(df, across(everything(), replace_last_0))
# or one by one
mutate(df, x = replace_last_0(x), 
           y = replace_last_0(y), 
           z = replace_last_0(z))
abichat
  • 2,317
  • 2
  • 21
  • 39
1

First we can create a simple tibble:

foo <- data.frame(x = 1:10, y = sample(c(-1,0,1), 10, replace = T)) |>
  tibble::as.tibble()

You can use which to identify elements in a vector that satisfy a condition, and then replace them.

dat$y[max(which(dat$y == 0))] <- 2
Pedro Alencar
  • 1,049
  • 7
  • 20