У нас есть data.frame d2_cleaned
> dput(d2_cleaned[1:3,c(2,4,5)])
structure(list(Customer.ID = c(110531L, 110531L, 110531L), Time.Spent.Watching = c(16032,
10919, 236), Video.ID.v26 = c(3661L, 4313L, 3661L)), .Names = c("Customer.ID",
"Time.Spent.Watching", "Video.ID.v26"), row.names = c(333515L,
333516L, 333522L), class = "data.frame")
>
У нас есть еще один df = distinct_customers_after_cleaning
, первый столбец уникален User.ID
, поэтому каждый пользователь представлен один раз.Остальные столбцы (игнорируйте col2) - это все уникальные фильмы.Df выглядит так:
> dput(distinct_customers_after_cleaning[1:5,1:5])
structure(list(Customer.ID = c(110531L, 318721L, 468491L, 568071L,
1390371L), Hits.After.Cleaning = c(58L, 44L, 98L, 6L, 5L), `3661` = c(0,
0, 0, 0, 0), `4313` = c(0, 0, 0, 0, 0), `3661.1` = c(0, 0, 0,
0, 0)), .Names = c("Customer.ID", "Hits.After.Cleaning", "3661",
"4313", "3661.1"), row.names = c(NA, 5L), class = "data.frame")
>
Мне нужно заполнить значения df diver_customers_after_cleaning.Чтобы сделать это, я хочу взять каждую строку Time.Spent.Watching из d2_cleaned и суммировать ее в нужном месте Different_customers_after_cleaning.Чтобы найти правильное место, мне нужно сопоставить идентификаторы пользователя и фильма: if (d2_cleaned [i, 'Customer.ID'] == Different_customers_after_cleaning [j, 'Customer.ID']) и if (d2_cleaned [i, 'Video.ID.v26 '] == names (different_customers_after_cleaning [y])) Вот циклы for, которые я использовал:
#fill in rows
for (j in 1 : 10000) {
print(j)
for (i in 1 : nrow(d2_cleaned)) {
if (d2_cleaned[i, 'Customer.ID'] == distinct_customers_after_cleaning[j, 'Customer.ID']) {
for (y in 1:ncol(distinct_customers_after_cleaning)) {
if (d2_cleaned[i, 'Video.ID.v26'] == names(distinct_customers_after_cleaning[y])) {
distinct_customers_after_cleaning[j, y] <- distinct_customers_after_cleaning[j, y] + d2_cleaned[i,'Time.Spent.Watching']
}
}
}
}
}
Хотя этот код работает так, как я хочу, он очень медленный (требуется 4 днячерез все данные).Не могли бы вы порекомендовать лучшее решение, возможно, включая aggregate
?