如何根据R中的日期填写缺失值?

时间:2018-09-20 14:25:53

标签: r tidyr

我有一个以下格式的数据框,它们代表我拥有的大数据集

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缺少几个值。基本上我想填写缺失的grade值基于year列,因此它类似于以下内容。

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

我当时想我的第一步是将year格式的factor列转换为日期格式。然后按顺序排列各列,并使用fill中的tidyr之类的内容来填充缺少的列。我应该如何去做,还是有更好的方法来解决这个问题?

1 个答案:

答案 0 :(得分:2)

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值,您不会有2个或更多连续的F.names