How do i add a new Category
into comb_df
where the value of this new
newcat
is sum of
Category = New
Jan 2014
+ Category = Old
Jan 2014
Category = c("New")
value = c(4,7,6)
Date= c ("Jan 2014", "Feb 2014", "Mar 2014")
#NonDaily = c(4, 7,6 ,8,9,10)
df1 <- data.frame(Category, Date,value, check.names = FALSE)
Category = c("Old")
value = c(1,2,4)
Date= c ("Jan 2014", "Feb 2014", "Mar 2014")
df2 <- data.frame(Category,Date, value,check.names = FALSE)
comb_df <- rbind(df1,df2)
Category Date value
1 New Jan 2014 4
2 New Feb 2014 7
3 New Mar 2014 6
4 Old Jan 2014 1
5 Old Feb 2014 2
6 Old Mar 2014 4
Expected Outcome
newcat =
Category = New
Jan 2014
+ Category = Old
Jan 2014
Category Date value
1 New Jan 2014 4
2 New Feb 2014 7
3 New Mar 2014 6
4 Old Jan 2014 1
5 Old Feb 2014 2
6 Old Mar 2014 4
7 newcat Jan 2014 5
8 newcat Feb 2014 9
9 newcat Mar 2014 10
library(dplyr)
comb_df %>%
add_row(Category = "newcat",
comb_df %>%
summarise(value = sum(value), .by = "Date")
)
Category Date value
1 New Jan 2014 4
2 New Feb 2014 7
3 New Mar 2014 6
4 Old Jan 2014 1
5 Old Feb 2014 2
6 Old Mar 2014 4
7 newcat Jan 2014 5
8 newcat Feb 2014 9
9 newcat Mar 2014 10
Base R
rbind(comb_df, data.frame(Category = "newcat", aggregate(value ~ Date, FUN = sum, data = comb_df)))
Category Date value
1 New Jan 2014 4
2 New Feb 2014 7
3 New Mar 2014 6
4 Old Jan 2014 1
5 Old Feb 2014 2
6 Old Mar 2014 4
7 newcat Feb 2014 9
8 newcat Jan 2014 5
9 newcat Mar 2014 10