Я не нашел способа сделать это, поэтому спрашиваю, есть ли более простой способ сделать это. Вот образец набора данных:
Revenue Product New Code
1 223,220.00 Apple
2 386,640.40 Apple
3 19,891.95 Apple
Мне нужно взять каждую строку дохода, распределить доход по разным процентам, а затем назначить каждый процент новому коду.
В качестве примера ,
Для Apple выручка должна быть распределена следующим образом:
- 0,45 переходит в «A».
- 0,50 идет в «B».
- 0,05 переходит в 'C'.
Итак, первое значение из набора данных, Revenue = 223220,00, должно быть распределено, как показано ниже:
Revenue Product New Code
1 100,449 Apple A
2 111,610 Apple B
3 11,161 Apple C
Это увеличится количество строк.
Я пробовал использовать этот код, но не знаете, есть ли более простой способ сделать это?
#
# 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'])