Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 views
in Technique[技术] by (71.8m points)

r - Assign NAs to Duplicates in each Row after first occurence

I have a dataframe that looks like this:

    crop1   crop4       crop5       crop6   crop7   crop8         crop9  crop10      crop11
1   Onion    Rice  Soya Beans  Sugar Cane   Onion     Tea  Corn (Maize)    Rice  Soya Beans
2    None    None        None        None    None    None          None    None        None
3    None    None        None        None    None    None          None    None        None
4 Accacia  Rubber     Accacia      Rubber Accacia  Rubber       Accacia  Rubber     Accacia
5 Accacia  Rubber     Accacia      Rubber Accacia  Rubber       Accacia  Rubber     Accacia
6    Rice    Rice        Rice        Rice    Rice    Rice          Rice    Rice        Rice

Now i would like to assign NAs to all repeated entries in each row after they first occured. That is, my dataframe should have just unique entries in each row, otherwise NAs. For example, in the first row I would like to have:

1   Onion    Rice  Soya Beans  Sugar Cane   NA    Tea  Corn (Maize)    NA  NA

As "Onion", "Rice" and "Soya Beans" have already occured in this row. Consequently, row 4 should look like this:

4 Accacia  Rubber NA NA NA NA NA NA NA

Any ideas on this?

Thank you!

Dataframe: http://pastebin.com/yKqhWyvW

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

We can use duplicated to set the duplicate elements as NA in each row by looping over the rows with apply

df1[] <- t(apply(df1, 1, FUN = function(x) replace(x, duplicated(x), NA)))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...