我有一个看起来像这样的数据集:
Type Age count1 count2 Year Pop1 Pop2 TypeDescrip
A 35 1 1 1990 30000 50000 alpha
A 35 3 1 1990 30000 50000 alpha
A 45 2 3 1990 20000 70000 alpha
B 45 2 1 1990 20000 70000 beta
B 45 4 5 1990 20000 70000 beta
Run Code Online (Sandbox Code Playgroud)
我想添加在Type和Age列中匹配的行的计数.理想情况下,我最终会得到一个如下所示的数据集:
Type Age count1 count2 Year Pop1 Pop2 TypeDescrip
A 35 4 2 1990 30000 50000 alpha
A 45 2 3 1990 20000 70000 alpha
B 45 6 6 1990 20000 …
Run Code Online (Sandbox Code Playgroud) 假设我有两个数据集.一个包含具有开始/结束日期的促销列表,另一个包含每个程序的月度销售数据.
promotions = data.frame(
start.date = as.Date(c("2012-01-01", "2012-06-14", "2012-02-01", "2012-03-31", "2012-07-13")),
end.date = as.Date(c("2014-04-05", "2014-11-13", "2014-02-25", "2014-08-02", "2014-09-30")),
program = c("a", "a", "a", "b", "b"))
sales = data.frame(
year.month.day = as.Date(c("2013-02-01", "2014-09-01", "2013-08-01", "2013-04-01", "2012-11-01")),
program = c("a", "b", "a", "a", "b"),
monthly.sales = c(200, 200, 200, 400, 200))
Run Code Online (Sandbox Code Playgroud)
注意,sales$year.month.day
用于表示年/月.包括日,因此R可以更简单地将列视为日期对象的向量,但它与实际销售无关.
我需要确定每个程序每月发生的促销数量.这是一个产生我想要的输出的循环示例:
sales$count = rep(0, nrow(sales))
sub = list()
for (i in 1:nrow(sales)) {
sub[[i]] = promotions[which(promotions$program == sales$program[i]),]
if (nrow(sub[[i]]) > 1) {
for (j in 1:nrow(sub[[i]])) { …
Run Code Online (Sandbox Code Playgroud)