I haven't found a way to do this, so asking if there's a simpler way to do this. Here's a sample of the data set:
Revenue Product New Code
1 223,220.00 Apple
2 386,640.40 Apple
3 19,891.95 Apple
I need to take each revenue row, allocate the revenue by different percentages and then assign each percentage to a new code.
As an example,
For Apple, the revenue should be allocated by:
- 0.45 goes to ‘A’.
- 0.50 goes to ‘B’.
- 0.05 goes to ‘C’.
So, the first value from the data set, Revenue =223,220.00 and should be allocated as below:
Revenue Product New Code
1 100,449 Apple A
2 111,610 Apple B
3 11,161 Apple C
This would increase the # of rows.
I tried using this code, but wondering if there's an easier way to do this?
#
# libraries
#
library(dplyr)
#
# load data
#
my_data <- read.csv('sales_data_to_reclassify.csv', stringsAsFactors = FALSE)
#
# get total category revenue
#
Apple_revenue <- sum(my_data[substr(my_data$product, 1, 4) == 'Apple', 'Revenue'])
Apple_rows <- which(substr(my_data$product, 1, 4) == 'Apple')
#
# set the splits
#
splits <- list(A = 0.45,
B = 0.50,
C = 0.05)
#
# apply the splits at row level
#
for (i in Apple_rows) {
#
# revenue for this row in the original data
#
row_revenue = my_data[i, 'Revenue']
for (label in names(splits)) {
#
# grab the row
#
new_row <- my_data[i, ]
#
# calculate the revenue for this split
# and update the new row
#
new_row$Revenue <- row_revenue * splits[[label]]
#
# assign the label
#
new_row$New.Code <- label
#
# build a temporary data frame to hold the new rows
#
if (label == names(splits)[1]) {
new_rows <- new_row
} else {
new_rows <- rbind(new_rows, new_row)
}
rownames(my_data) <- NULL
Apple_rows <- which(substr(my_data$product, 1, 4) == 'Apple')
}
#
# drop the original row
#
my_data <- my_data[-i, ]
#
# add in the new rows
#
my_data <- rbind(my_data, new_rows)
}
#
# test revenue
#
Apple_new_revenue <- sum(my_data[substr(my_data$product, 1, 4) == 'Apple', 'Revenue'])