我們可以使用data.table
。將'data.frame'轉換爲'data.table'(setDT(df1)
)。基於'SALE_PRICE'(!SALE_PRICE
)中存在0的邏輯向量創建一個分組變量rleid
。使用'grp'作爲分組變量,我們得到'Data.table(.SD[.N]
)if
'SALE_PRICE elements are
全部0 or
else get the
.SD'的最後一行,即特定組的全行。
library(data.table)
setDT(df1)[, grp:= rleid(!SALE_PRICE)
][,if(all(!SALE_PRICE)) .SD[.N] else .SD , grp
][, grp := NULL][]
# WEEK PRICE QUANTITY SALE_PRICE TYPE
# 1: 4992 5.99 2847.50 0.00 3
# 2: 4995 3.33 36759.00 3.33 3
# 3: 4997 5.49 2858.50 0.00 3
# 4: 5001 3.33 32425.00 3.33 3
# 5: 5004 5.99 4329.50 0.00 3
# 6: 5006 2.74 55811.00 2.74 3
# 7: 5008 5.99 4074.00 0.00 3
# 8: 5009 3.99 12125.25 3.99 3
# 9: 5017 2.74 77645.00 2.74 3
#10: 5018 5.49 5315.50 0.00 3
#11: 5020 2.74 78699.00 2.74 3
#12: 5024 5.49 6545.00 0.00 3
#13: 5025 3.33 63418.00 3.33 3
或使用dplyr
通過創建diff
和cumsum
,然後filter
行分組變量只保留是0或(|
)「SALE_PRICE」的最後一排選擇行,其中一個選項'SALE_PRICE'不是0.
library(dplyr)
df1 %>%
group_by(grp = cumsum(c(TRUE,diff(!SALE_PRICE)!=0))) %>%
filter(!duplicated(!SALE_PRICE, fromLast=TRUE)|SALE_PRICE!=0) %>%
select(-grp)
# grp WEEK PRICE QUANTITY SALE_PRICE TYPE
# (int) (int) (dbl) (dbl) (dbl) (int)
#1 1 4992 5.99 2847.50 0.00 3
#2 2 4995 3.33 36759.00 3.33 3
#3 3 4997 5.49 2858.50 0.00 3
#4 4 5001 3.33 32425.00 3.33 3
#5 5 5004 5.99 4329.50 0.00 3
#6 6 5006 2.74 55811.00 2.74 3
#7 7 5008 5.99 4074.00 0.00 3
#8 8 5009 3.99 12125.25 3.99 3
#9 8 5017 2.74 77645.00 2.74 3
#10 9 5018 5.49 5315.50 0.00 3
#11 10 5020 2.74 78699.00 2.74 3
#12 11 5024 5.49 6545.00 0.00 3
#13 12 5025 3.33 63418.00 3.33 3
你是怎麼得到這個錯誤的?如果(price.hierarchy $ SALE_PRICE [i] == 0&price.hierarchy $ SALE_PRICE [i + 1] == 0) – akrun
{i in 1 :(nrow(price.hierarchy)-1)){ { price.hierarchy < - price.hierarchy [-i,] } else price.hierarchy } – sayali