代码之家  ›  专栏  ›  技术社区  ›  Nathan123

如何根据R中的日期填充缺少的值?

  •  1
  • Nathan123  · 技术社区  · 6 年前

    F.names<-c('M','M','M','A','A')
    L.names<-c('Ab','Ab','Ab','Ac','Ac')
    year<-c('August 2015','September 2014','September 2016', 'August 2014','September 2013')
    grade<-c(NA,'9th Grade','11th Grade',NA,'11th grade')
    
    df.have<-data.frame(F.names,L.names,year,grade)
    
    F.names L.names           year      grade
    1       M      Ab    August 2015       <NA>
    2       M      Ab September 2014  9th Grade
    3       M      Ab September 2016 11th Grade
    4       A      Ac    August 2014       <NA>
    5       A      Ac September 2013 11th grade
    

    这个 year factor 在原始数据集中设置格式,并且有几个缺少的值 grade 基本上我想补上缺的 等级 基于的值

    F.names L.names           year      grade
    1       M      Ab    August 2015 10th Grade
    2       M      Ab September 2014  9th Grade
    3       M      Ab September 2016 11th Grade
    4       A      Ac    August 2014 12th Grade
    5       A      Ac September 2013 11th grade
    

    我在想我的第一步应该是隐藏 fill tidyr 以填充缺少的列。我该怎么做呢,还是有更好的方法?

    1 回复  |  直到 6 年前
        1
  •  2
  •   AntoniosK    6 年前
    F.names<-c('M','M','M','A','A')
    L.names<-c('Ab','Ab','Ab','Ac','Ac')
    year<-c('August 2015','September 2014','September 2016', 'August 2014','September 2013')
    grade<-c(NA,'9th Grade','11th Grade',NA,'11th grade')
    
    df.have<-data.frame(F.names,L.names,year,grade)
    
    library(tidyverse)
    
    df.have %>%
      separate(year, c("m","y"), convert = T, remove = F) %>%
      separate(grade, c("num","type"), sep="th", convert = T) %>%
      arrange(F.names, y) %>%
      group_by(F.names) %>%
      mutate(num = ifelse(is.na(num), lag(num) + 1, num),
             type = "grade") %>%
      ungroup() %>%
      unite(grade, num, type, sep="th ") %>%
      select(-m, -y)
    
    #   F.names L.names           year      grade
    # 1       A      Ac September 2013 11th grade
    # 2       A      Ac    August 2014 12th grade
    # 3       M      Ab September 2014  9th grade
    # 4       M      Ab    August 2015 10th grade
    # 5       M      Ab September 2016 11th grade
    

    NA 对一个给定的 F.names