Rohan Bali
Rohan Bali

Reputation: 157

Keeping values of first occurrence in r

The data is as follows:

   a <- c("A","A","A","B","C","B","B","D")
b <- c('D1',"D2","D1","D1","A1","A2","A3","A2")
c <- c(123,145,223,123,5656,34,23432,6565)

df <- data.frame(a,b,c)

The output should have 'a' and 'b' column as it is. The values of column 'c' should become 0 if it is the second occurrence element from column 'a'. For example the second and third value in column c is 145 and 223 should become 0 and 0 because the first occurrence of A is 123.

Sample output is as follows: enter image description here

Upvotes: 1

Views: 394

Answers (1)

akrun
akrun

Reputation: 887048

Create a logical vector with duplicated on the 'a' column and use that to to replace the values in 'c' to 0

df$c[duplicated(df$a)] <- 0

-output

df
#  a  b    c
#1 A D1  123
#2 A D2    0
#3 A D1    0
#4 B D1  123
#5 C A1 5656
#6 B A2    0
#7 B A3    0
#8 D A2 6565

Or another option is a group by replace

library(dplyr)
df %>%
   group_by(a) %>% 
   mutate(c = replace(c, row_number() > 1, 0)) %>%
   ungroup

Upvotes: 1

Related Questions