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!
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))
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