AntonCH
AntonCH

Reputation: 312

for each id na in value

I have dataframe:

id    value
19      56
19      56
19      56
19      98
19      98

The id column has many different meanings, not just 19. I need to do this:

id    value
19     56
19     NA
19     NA
19     98
19     NA

And so for each id.

Upvotes: 0

Views: 46

Answers (2)

mtoto
mtoto

Reputation: 24188

You could use replace():

df %>% group_by(id) %>% 
  mutate(test = replace(value, duplicated(value), NA))
#     id value  test
#  <int> <int> <int>
#1    19    56    56
#2    19    56    NA
#3    19    56    NA
#4    19    98    98
#5    19    98    NA

Upvotes: 2

akrun
akrun

Reputation: 887128

We can use duplicated from base R to create a logical index to assign the 'value' to NA

df1$value[duplicated(df1)] <- NA
df1
#  id value
#1 19    56
#2 19    NA
#3 19    NA
#4 19    98
#5 19    NA

Upvotes: 3

Related Questions