代码之家  ›  专栏  ›  技术社区  ›  Tim Wilcox

如何缩小R中的数据帧

  •  2
  • Tim Wilcox  · 技术社区  · 5 年前

    这里是手工创建的数据。有三个领域;状态、代码类型和代码。这样做的原因是,我正试图将它的一个更扩展的版本连接到一个由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。如何告诉它删除两位数的所有非唯一值?

    1 回复  |  直到 5 年前
        1
  •  1
  •   akrun    5 年前

    我们可以用 distinct 并指定 .keep_all

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

    另一种选择是使用 duplicated 在里面 filter

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

    为了提高效率,可以使用 data.table

    library(data.table)
    setDT(industry)[!duplicated(substr(code, 1, 2))]
    
        2
  •  0
  •   jpdugo17    5 年前

    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
    

    于2021-06-10由 reprex package (2.0.0版)

    推荐文章