我有一个数据
WEEK PRICE QUANTITY SALE_PRICE
4992 3.49 1908.750 0.00
4999 2.50 5681.000 2.50
5001 3.00 3187.000 3.00
5002 3.49 1455.000 0.00
5008 2.69 2263.500 2.69
5011 3.49 1515.500 0.00
5013 2.69 3297.000 2.69
5015 3.49 1059.500 0.00
5023 2.50 6056.000 2.50
5024 3.00 1954.500 3.00
5026 3.49 1163.833 0.00
5037 2.50 6797.000 2.50
5038 3.00 2109.000 3.00
5040 2.50 4521.000 2.50
5041 3.33 2469.000 3.33
我想仅在具有销售价格的行之前不存在销售价格为 0 的行的地方,在非零销售价格之前重复最后观察到的销售价格为 0 的行。输出应如下所示:
WEEK PRICE QUANTITY SALE_PRICE TYPE
4992 3.49 1908.750 0.00 3
4999 2.50 5681.000 2.50 3
4992 3.49 1908.750 0.00 3
5001 3.00 3187.000 3.00 3
5002 3.49 1455.000 0.00 3
5008 2.69 2263.500 2.69 3
5011 3.49 1515.500 0.00 3
5013 2.69 3297.000 2.69 3
5015 3.49 1059.500 0.00 3
5023 2.50 6056.000 2.50 3
5015 3.49 1059.500 0.00 3
5024 3.00 1954.500 3.00 3
5026 3.49 1163.833 0.00 3
5037 2.50 6797.000 2.50 3
5026 3.49 1163.833 0.00 3
5038 3.00 2109.000 3.00 3
5026 3.49 1163.833 0.00 3
5040 2.50 4521.000 2.50 3
5026 3.49 1163.833 0.00 3
5041 3.33 2469.000 3.33 3
Data
structure(list(WEEK = c(4992L, 4999L, 5001L, 5002L, 5008L, 5011L,
5013L, 5015L, 5023L, 5024L, 5026L, 5037L, 5038L, 5040L, 5041L
), PRICE = c(3.49, 2.5, 3, 3.49, 2.69, 3.49, 2.69, 3.49, 2.5,
3, 3.49, 2.5, 3, 2.5, 3.33), QUANTITY = c(1908.75, 5681, 3187,
1455, 2263.5, 1515.5, 3297, 1059.5, 6056, 1954.5, 1163.833, 6797,
2109, 4521, 2469), SALE_PRICE = c(0, 2.5, 3, 0, 2.69, 0, 2.69,
0, 2.5, 3, 0, 2.5, 3, 2.5, 3.33)), .Names = c("WEEK", "PRICE",
"QUANTITY", "SALE_PRICE"), class = "data.frame", row.names = c(NA,
-15L))
我努力了
if(nrow(price.hierarchy) > 2) {
for(i in 2: (nrow(price.hierarchy) - 1)) {
if(price.hierarchy$SALE_PRICE[i] !=0 & price.hierarchy$SALE_PRICE[i+1] !=0 & price.hierarchy$SALE_PRICE[i-1]==0) {
price.hierarchy1 <- price.hierarchy[which(price.hierarchy[, 1] > price.hierarchy[i,1]), ]
price.hierarchy[i+1, ] <- NA
price.hierarchy[i+1, ] <- price.hierarchy[i-1, ]
price.hierarchy2 <- price.hierarchy[which(price.hierarchy[, 1] < price.hierarchy[i+2,1]), ]
price.hierarchy <- rbind(price.hierarchy2, price.hierarchy1)
}
else
price.hierarchy
}
}
这使:
> price.hierarchy
WEEK PRICE QUANTITY SALE_PRICE
1 4992 3.49 1908.750 0.00
2 4999 2.50 5681.000 2.50
3 4992 3.49 1908.750 0.00
31 5001 3.00 3187.000 3.00
4 5002 3.49 1455.000 0.00
5 5008 2.69 2263.500 2.69
6 5011 3.49 1515.500 0.00
7 5013 2.69 3297.000 2.69
8 5015 3.49 1059.500 0.00
9 5023 2.50 6056.000 2.50
10 5015 3.49 1059.500 0.00
101 5024 3.00 1954.500 3.00
11 5026 3.49 1163.833 0.00
12 5037 2.50 6797.000 2.50
13 5026 3.49 1163.833 0.00
131 5038 3.00 2109.000 3.00
14 5040 2.50 4521.000 2.50
15 5041 3.33 2469.000 3.33