i'm a new user and i need a lil help My df looks like this
y v
1 2000 1
2 2003 3
3 2005 3
4 2006 6
5 2009 1
6 2011 1
7 2013 3
I wanna add years that don't appear among the years vector and put it's approriate v value by 0's. Like 2001,2002.. for instance;
y v
1 2000 1
2 2001 0
3 2002 0
4 2003 3
5 2004 0
6 2005 3
my first try was to create another vector using the library chron
here's my code,
yy <- seq.dates(from="01/01/2000", to="12/31/2013", by="years")
yy <- as.POSIXct(yy, f="%Y")
yy <- format(yy, f ="%Y")
pp <- rep(0, length=14)
yp <- data.frame(cbind(yy, pp))
but since they don't have the same length, i couldn't replace the values from DF to yp when they years are the same!
Thanks in advance
You could use merge for this:
DF <- read.table(text=" y v
1 2000 1
2 2003 3
3 2005 3
4 2006 6
5 2009 1
6 2011 1
7 2013 3",header=TRUE)
DF <- merge(DF,
data.frame(y=seq.int(min(DF$y),max(DF$y))),
by="y",all=TRUE)
DF$v[is.na(DF$v)] <- 0 #assuming you have no other NA values
head(DF)
# y v
# 1 2000 1
# 2 2001 0
# 3 2002 0
# 4 2003 3
# 5 2004 0
# 6 2005 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With