data.table. , , "", , sub "" sum "".
library(data.table)
setDT(theDF)[,.(stock = sum(stock)) , .(dates, fruits = sub("([0-9]|[A-Z])$", "", parts))]
dplyr, .
library(dplyr)
theDF %>%
group_by(dates, fruits = sub('([0-9]|[A-Z])$', '', parts)) %>%
summarise(stock = sum(stock))
Update
"", vector, %chin%, "i", (:=) "", "i", "", "", "" sum "".
setDT(theDF)[as.character(fruits) %chin% c("Grape", "Kiwi"),
fruits := parts][, .(stock = sum(stock)), .(dates, fruits)]
theDF <- structure(list(dates = structure(c(16971, 16971, 16971, 16971,
16971, 16971, 16971, 16971, 16971, 16971, 16971, 16971, 16971,
16971, 16971, 16971, 16971, 16971, 16971, 16971), class = "Date"),
fruits = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 5L,
5L, 5L, 5L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L), .Label = c("Apple",
"Banana", "Grape", "Kiwi", "Strawberry"), class = "factor"),
parts = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 14L,
15L, 16L, 16L, 11L, 10L, 10L, 10L, 9L, 13L, 9L, 12L), .Label = c("Apple1",
"Apple2", "Apple3", "Apple4", "Banana1", "Banana2", "Banana3",
"Banana4", "Big Kiwi", "Blue Grape", "Green Grape", "Middle Kiwi",
"Small Kiwi", "StrawberryX", "StrawberryY", "StrawberryZ"
), class = "factor"), stock = c(8, 19, 15, 4, 6, 18, 1, 10,
9, 16, 11, 2, 12, 13, 5, 3, 17, 14, 20, 7)), .Names = c("dates",
"fruits", "parts", "stock"), row.names = c(NA, -20L), class = "data.frame")