Replace the first duplicated data in a row of dataframe with NA

Viewed 79

I find that rows in my dataframe 'Data' often have the 1st element equal 2nd element. I want to replace this 1st element that is duplicated with NA and keep the 2nd element.

My dataframe 'Data' with 3 columns c1, c2 and c3 like this

c1 c2 c3
1  1  4
5  2  9
3  1  8
7  7  2
9  9  1

I tried to run this code

for (i in 1:length(Data)) {
Data[i,1]<- if (Data[i,1]==Data[i,2]) NA else Data[i,1]
}

but it doesn't work. I would like to use Data[i;1] instead of Data$c1[i] because i use loops of merge() to recreate my dataframe and the name of the columns change every time the dataframe is recreate.
I want to replace any value in column c1 which is duplicated in the same row of column c2 by NA, like this

c1 c2 c3
NA 1  4
5  2  9
3  1  8
NA 7  2
NA 9  1

Could you help me, please? Thank you so much.

2 Answers

You can do this:


df[df$c1 == df$c2, 1] <- NA

 c1 c2 c3
1 NA  1  4
2  5  2  9
3  3  1  8
4 NA  7  2
5 NA  9  1

With dplyr:

df %>% 
   mutate(c1=ifelse(c1==c2,NA,c1))
  c1 c2 c3
1 NA  1  4
2  5  2  9
3  3  1  8
4 NA  7  2
5 NA  9  1
Related