Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

The following is the data frame that I have created:

id <- c(1, 1, 1, 2, 2, 2, 3, 3, 3)

x <- c(1, 1, 0, 0, 1, 1, 1, 1, 1)

df <- data.frame(id, x)

From that data frame, I just only wanted to keep only the first value that is equal to 1 for each id, otherwise, I want it to be 0. My desired output should look like this:

     id     x

  <dbl> <dbl>

1     1     1

2     1     0

3     1     0

4     2     0

5     2     1

6     2     0

7     3     1

8     3     0

9     3     0

I have tried this code, but I am not getting the output:

df %>% 

  group_by(id) %>%

  mutate(x = if (any(x == 1)) replace(x,

                                      row_number() != 1, 0) else x)

1 Answer

0 votes
by (108k points)

In R programming you can use replace inside the mutate function. Refer to the following:

library(dplyr)

df %>% group_by(id) %>% mutate(y = replace(x, -match(1L, x), 0L))

OR

#mutate(y = replace(x, which.max(x), 0L))

#     id     x     y

#  <dbl> <dbl> <dbl>

#1     1     1     1

#2     1     1     0

#3     1     0     0

#4     2     0     0

#5     2     1     1

#6     2     1     0

#7     3     1     1

#8     3     1     0

#9     3     1     0

Browse Categories

...