【问题标题】:How to narrow down data frame in R [duplicate]如何缩小R中的数据框[重复]
【发布时间】:2021-08-27 23:18:06
【问题描述】:

请原谅我不太完美的标题,但在理解这一点时遇到了一些问题。

这里是手动创建的数据。共有三个字段;状态、代码类型和代码。这样做的原因是我试图将其更广泛的版本加入到由 160 万行组成的数据框中,并遇到内存不足的问题。我的想法是,我会大大减少这张表的行数;行业。

state <- c(32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32)
codetype <- c(10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10)
code <- c(522,523,524,532,533,534,544,545,546,551,552,552,561,562,563,571,572,573,574)



industry = data.frame(state,codetype,code)

所需的结果将是一个双重操作。首先,我会将六位数代码缩短为 2。这是通过。

industry<-industry %>% mutate(twodigit = substr(code,1,2). 

这将产生第五列,两位数。目前有19个值。但只有 7 个唯一值的两位数; 52,53,54,55,56,57。如何告诉它删除两位数的所有非唯一值?

【问题讨论】:

  • 你需要industry %&gt;% distinct(twodigit, .keep_all = TRUE)
  • @akrun,把这个写成答案。是的,它成功了,感谢您的帮助。

标签: r dplyr duplicates


【解决方案1】:

我们可以使用distinct 并将.keep_all 指定为TRUE 来获取整个列

library(dplyr)
industry %>%
   distinct(twodigit, .keep_all = TRUE)

另一种选择是在filter 中使用duplicated

industry %>%
    filter(!duplicated(twodigit))

为了提高效率,也许使用data.table 方法

library(data.table)
setDT(industry)[!duplicated(substr(code, 1, 2))]

【讨论】:

    【解决方案2】:

    使用unique() 方法:

    library(tidyverse)
    
    state <- c(32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32)
    codetype <- c(10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10)
    code <- c(522,523,524,532,533,534,544,545,546,551,552,552,561,562,563,571,572,573,574)
    industry = data.frame(state,codetype,code)
    industry<-industry %>% mutate(twodigit = substr(code,1,2))
    
    
    unique(industry$twodigit) %>%
        map_dfr(~filter(industry, twodigit == .x)[1, ])
    #>   state codetype code twodigit
    #> 1    32       10  522       52
    #> 2    32       10  532       53
    #> 3    32       10  544       54
    #> 4    32       10  551       55
    #> 5    32       10  561       56
    #> 6    32       10  571       57
    

    reprex package (v2.0.0) 于 2021-06-10 创建

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-04
      • 1970-01-01
      • 2012-11-13
      • 2019-04-11
      • 2015-11-03
      相关资源
      最近更新 更多