dataframe - Reshape the Columns of Data Frame in R -


i have 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 week number in year , 'bags' denotes number of bags used small firm. want data frame in form of week bags 1 0 2 0 3 0 4 5 5 0 6 3 7 0 8 0 9 0 10 5 , on, in order plot weekly changes in number of bags. sure silly question not find way. please in direction.

you can create dataset

df2 <- data.frame(week= 1:max(df1$week)) 

and merge 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][] 

Comments

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -