【问题标题】:Assign NAs to Duplicates in each Row after first occurence首次出现后将 NA 分配给每行中的重复项
【发布时间】:2017-06-27 18:58:54
【问题描述】:

我有一个如下所示的数据框:

    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

现在我想在它们第一次出现后将 NA 分配给每行中的所有重复条目。也就是说,我的数据框应该在每一行中只有唯一的条目,否则 NAs。例如,在第一行我想要:

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

由于“洋葱”、“米饭”和“大豆”已经出现在这一行。因此,第 4 行应如下所示:

4 Accacia  Rubber NA NA NA NA NA NA NA

对此有何想法?

谢谢!

数据框:http://pastebin.com/yKqhWyvW

【问题讨论】:

    标签: r duplicates


    【解决方案1】:

    我们可以使用duplicated 将每行中的重复元素设置为NA,方法是循环使用apply

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

    【讨论】:

      猜你喜欢
      • 2014-06-28
      • 1970-01-01
      • 1970-01-01
      • 2022-12-11
      • 2021-09-28
      • 2016-07-24
      • 2016-09-05
      相关资源
      最近更新 更多