I have a data frame (for example)
Week Bags
4 5
6 3
10 5
13 7
18 5
23 1
30 9
31 9
32 4
33 7
35 1
38 2
42 2
47 2
'Week' column denotes the week number in an year and 'Bags' denotes the number of bags used by a small firm. I want my data frame in the form of Week Bags 1 0 2 0 3 0 4 5 5 0 6 3 7 0 8 0 9 0 10 5
and so on, in order to plot the weekly changes in number of bags. I am sure it is very silly question but I could not find any way. Please help in this direction.
You can create another dataset
df2 <- data.frame(Week= 1:max(df1$Week))
and then merge
with the first dataset
res<- merge(df1, df2, all=TRUE)
res$Bags[is.na(res$Bags)] <- 0
head(res,10)
# Week Bags
#1 1 0
#2 2 0
#3 3 0
#4 4 5
#5 5 0
#6 6 3
#7 7 0
#8 8 0
#9 9 0
#10 10 5
Or using data.table
library(data.table)
res1 <- setDT(df1, key='Week')[J(Week = 1:max(Week))][is.na(Bags), Bags:=0][]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.