17

I have binary data as below:

ID <- c("A", "B", "C", "D", "E", "F")
Q0 <- c(0, 0, 0, 0, 0, 0)
Q1 <- c(0, 1, 0, 0, NA, 1) 
Q2 <- c(0, NA, 1, 0, NA, 1) 
Q3 <- c(0, NA, NA, 1, NA, 1) 
Q4 <- c(0, NA, NA, 1, NA, 1)

dta <- data.frame(ID, Q0, Q1, Q2, Q3, Q4)

If there is 1 for a row in one of the columns, all the subsequent columns should be 1 as well. If there is 0 or NA, the next column should stay as is.

Stated differently, how can I change the value of multiple columns based conditionally on the value of a column in a relative position?

The intended output for the above data frame is:

ID    Q0    Q1    Q2    Q3    Q4
A     0     0     0     0     0
B     0     1     1     1     1
C     0     0     1     1     1
D     0     0     0     1     1
E     0     NA    NA    NA    NA
F     0     1     1     1     1

How can I do this? Perhaps using apply or a for loop?

5
  • Your question has been closed for seeking opinions, which is a reasonable closure given the request for a more "elegant" solution. I've removed your attempt from the question entirely, and converted it to a "how-to" question. Since you have a working solution, you can actually go ahead and post it as a solution to this question if you want to.
    – cigien
    Commented Jul 6, 2022 at 20:15
  • 1
    Note: please keep in mind that the original version of this question provided a working solution and asked for something "more elegant". Such question should not be asked (and certainly not answered) here. Stack Overflow is for specific, objective, practical programming problems/questions. Questions asking for improvements to existing, working code should be asked on Code Review instead.
    – TylerH
    Commented Jul 6, 2022 at 20:27
  • @TylerH As with any question, we do make guesses repeatedly about what the asker wants based on the actual words in the question. It's not irrational to interpret "more elegant" as better performance and/or lesser code. Code review questions are not off topic here either.
    – TheMaster
    Commented Jul 6, 2022 at 21:00
  • 1
    @TheMaster A few things: you should not make guesses... if you have to guess, that means the question needs more detail, not an answer. You are right, it is not irrational to interpret more elegant as asking for better performance or fewer LoC. In fact, that example beautifully illustrates why we don't allow such opinionated questions. Your answer may provide better performance, and my answer may provide fewer LoC. Which one is what OP wants? What does OP mean by elegant? It is OP's responsibility and requirement to clarify this, before FGITWs jump in and provide a guess.
    – TylerH
    Commented Jul 6, 2022 at 21:15
  • 1
    @TheMaster Finally, questions asking for specific performance improvements, which is what that Meta question is about, are on-topic here if they are, as mentioned above, specific and objectively answerable. Code Review questions are a broader subject and are not on-topic here (and are not what that Meta question discusses, either).
    – TylerH
    Commented Jul 6, 2022 at 21:16

8 Answers 8

9

Yet another dplyr + purrr option could be:

dta %>%
 mutate(pmap_dfr(across(-ID), ~ `[<-`(c(...), seq_along(c(...)) > match(1, c(...)), 1)))

  ID Q0 Q1 Q2 Q3 Q4
1  A  0  0  0  0  0
2  B  0  1  1  1  1
3  C  0  0  1  1  1
4  D  0  0  0  1  1
5  E  0 NA NA NA NA
6  F  0  1  1  1  1
2
  • 1
    Cold you comment this solution ? I use dplyr often but lots of to unpack here
    – Julien
    Commented Jul 26, 2022 at 11:09
  • First what is the [<- function ?
    – Julien
    Commented Jul 26, 2022 at 11:09
9

Keeping things simple with a loop:

for (i in 3:ncol(dta)) dta[[i]][dta[[i-1]] == 1] <- 1
    #   ID Q0 Q1 Q2 Q3 Q4
    # 1  A  0  0  0  0  0
    # 2  B  0  1  1  1  1
    # 3  C  0  0  1  1  1
    # 4  D  0  0  0  1  1
    # 5  E  0 NA NA NA NA
    # 6  F  0  1  1  1  1

With dplyr + data.table inspired by Yuriy:

library(dplyr)
library(data.table)
setDT(dta)

dta[, (names(dta)[-1]) := as.list(cumany(.SD == 1)), by = ID]
8

An option with na.locf

library(zoo)
i1 <- do.call(pmax, c(dta[-1], na.rm = TRUE))!= 0
dta[-1][i1,] <- t(na.locf(as.data.frame(t(dta[-1][i1,]))))

-output

> dta
  ID Q0 Q1 Q2 Q3 Q4
1  A  0  0  0  0  0
2  B  0  1  1  1  1
3  C  0  0  1  1  1
4  D  0  0  0  1  1
5  E  0 NA NA NA NA
6  F  0  1  1  1  1
8

I found one more with pivoting:

library(tidyr)
library(dplyr)

dta %>% 
  pivot_longer(-ID) %>% 
  group_by(ID) %>% 
  mutate(value2 = value) %>% 
  fill(value2) %>% 
  mutate(value = ifelse(value2 == 0, value, value2)) %>% 
  select(-value2) %>% 
  pivot_wider(names_from = name, values_from = value)
  ID       Q0    Q1    Q2    Q3    Q4
  <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
1 A         0     0     0     0     0
2 B         0     1     1     1     1
3 C         0     0     1     1     1
4 D         0     0     0     1     1
5 E         0    NA    NA    NA    NA
6 F         0     1     1     1     1
5

Another possible solution:

library(dplyr)

dta %>% 
  mutate(t(apply(.[-1], 1, \(x) {if (max(x, na.rm = T) == 1) 
    x[which.max(x):length(x)] <- 1 else x; x})) %>% as_tibble)

#>   ID Q0 Q1 Q2 Q3 Q4
#> 1  A  0  0  0  0  0
#> 2  B  0  1  1  1  1
#> 3  C  0  0  1  1  1
#> 4  D  0  0  0  1  1
#> 5  E  0 NA NA NA NA
#> 6  F  0  1  1  1  1
5
ID <- c("A", "B", "C", "D", "E", "F")
Q0 <- c(0, 0, 0, 0, 0, 0)
Q1 <- c(0, 1, 0, 0, NA, 1) 
Q2 <- c(0, NA, 1, 0, NA, 1) 
Q3 <- c(0, NA, NA, 1, NA, 1) 
Q4 <- c(0, NA, NA, 1, NA, 1)

df <- data.frame(ID, Q0, Q1, Q2, Q3, Q4)

df[-1] <- t(apply(df[-1], 1, function(x) +(dplyr::cumany(x == 1))))
df
#>   ID Q0 Q1 Q2 Q3 Q4
#> 1  A  0  0  0  0  0
#> 2  B  0  1  1  1  1
#> 3  C  0  0  1  1  1
#> 4  D  0  0  0  1  1
#> 5  E  0 NA NA NA NA
#> 6  F  0  1  1  1  1

Created on 2022-07-04 by the reprex package (v2.0.1)

3
  • Can you explain the +(...) ? I have never encountered this notation
    – Julien
    Commented Jul 31, 2022 at 23:08
  • 1
    this is a conversion of TRUE to 1 and FALSE to 0. for example, run +TRUE or +FALSE Commented Aug 1, 2022 at 7:38
  • I run without the parenthesis in function(x) + dplyr::cumany(x == 1) and it works
    – Julien
    Commented Aug 1, 2022 at 8:01
5

You can create all the variables in the same mutate

dta %>% 
  mutate(
  Q2 = case_when(Q1 == 1 ~ 1, TRUE ~ Q2), 
  Q3 = case_when(Q2 == 1 ~ 1, TRUE ~ Q3),
  Q4 = case_when(Q3 == 1 ~ 1, TRUE ~ Q4))

  ID Q0 Q1 Q2 Q3 Q4
1  A  0  0  0  0  0
2  B  0  1  1  1  1
3  C  0  0  1  1  1
4  D  0  0  0  1  1
5  E  0 NA NA NA NA
6  F  0  1  1  1  1

But I don't know if it's possible to do this more programmatically

4

Here is a base R way with apply.

dta[-1] <- t(apply(dta[-1], 1, \(x) {
  y <- x
  y[is.na(y)] <- 0
  y <- as.integer(cumsum(y) > 0)
  is.na(y) <- is.na(x) & y == 0
  y
}))
dta
#>   ID Q0 Q1 Q2 Q3 Q4
#> 1  A  0  0  0  0  0
#> 2  B  0  1  1  1  1
#> 3  C  0  0  1  1  1
#> 4  D  0  0  0  1  1
#> 5  E  0 NA NA NA NA
#> 6  F  0  1  1  1  1

Created on 2022-07-04 by the reprex package (v2.0.1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.