Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
715 views
in Technique[技术] by (71.8m points)

r - Inserting missing years to complete a data.frame

I'm creating a dataframe containing the number of incidents of a certain kind in each state in each year from 2000 to 2010 (pretend that they are gun incidents):

states <- c('Texas', 'Texas', 'Arizona', 'California', 'California')
incidents <- c(1, 1, 2, 1, 4)
years <- c(2000, 2008, 2004, 2002, 2007)

DF <- data.frame(states, incidents, years)

> DF
      states incidents years
1      Texas         1  2000
2      Texas         1  2008
3    Arizona         2  2004
4 California         1  2002
5 California         4  2007

I want to insert rows to complete the dataset, e.g. zeros for Texas for 2001, 2002, 2003, ... 2007, and for 2009 and 2010. And likewise, zeros for Arizona for all years except 2004. Same thing for California.

How can I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use tidyr::complete to fill in missing years (2010:2010) and values with 0.

library(tidyr)
DFfilled <- DF %>%
    complete(states, years = 2000:2010, 
             fill = list(incidents = 0)) %>%
    as.data.frame()

PS:
If there are entries with year 2010 in your data (now it's only up to 2008) you can use full_seq(years, 1) instead of 2000:2010.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...