我有数据集
df=structure(list(SKU = c(11202L, 11202L, 11202L, 11202L, 11202L,
11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L,
11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L
), stuff = c(8.85947691, 9.450108704, 10.0407405, 10.0407405,
10.63137229, 11.22200409, 11.22200409, 11.81263588, 12.40326767,
12.40326767, 12.40326767, 12.99389947, 13.58453126, 14.17516306,
14.76579485, 15.94705844, 17.12832203, 17.71895382, 21.26274458,
25.98779894, 63.19760196), action = c(0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L),
acnumber = c(137L, 137L, 137L, 137L, 137L, 137L, 137L, 137L,
137L, 137L, 137L, 137L, 137L, 137L, 137L, 137L, 137L, 137L,
137L, 137L, 137L), year = c(2018L, 2018L, 2018L, 2018L, 2018L,
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L,
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L)), .Names = c("SKU",
"stuff", "action", "acnumber", "year"), class = "data.frame", row.names = c(NA,
-21L))
操作列只有两个值 0 和 1。 正如我们所看到的,1 类别的内容有 3 个观测值,0 类别的内容有 18 个观测值。
我需要
-
仅计算类别 1 的 stuff 变量的中位数(等于 25.98779894),不带零。
正如我们所看到的,一之间有零,它们需要被删除,如果存在负值,也需要被删除。
即,就好像数据集是这样的:
structure(list(SKU = c(11202L, 11202L, 11202L, 11202L, 11202L,
11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L,
11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L
), stuff = c(8.85947691, 9.450108704, 10.0407405, 10.0407405,
10.63137229, 11.22200409, 11.22200409, 11.81263588, 12.40326767,
12.40326767, 12.40326767, 12.99389947, 13.58453126, 14.17516306,
14.76579485, 15.94705844, 17.12832203, 17.71895382, 21.26274458,
25.98779894, 63.19760196), action = c(0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 1L, NA, NA, NA, NA, NA, NA, NA, NA, 1L, 1L),
acnumber = c(137L, 137L, 137L, 137L, 137L, 137L, 137L, 137L,
137L, 137L, 137L, 137L, 137L, 137L, 137L, 137L, 137L, 137L,
137L, 137L, 137L), year = c(2018L, 2018L, 2018L, 2018L, 2018L,
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L,
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L)), .Names = c("SKU",
"stuff", "action", "acnumber", "year"), class = "data.frame", row.names = c(NA,
-21L))
我还需要通过类别 0 的填充变量计算最后三个观察值的中位数,该变量位于第一个观察值之前, 在我们的例子中是 12,40326767
然后从类别 1 的中位数中减去类别 0 的中位数,然后乘以 1 的数量,在本例中为 3。
(25,98779894-12,40326767)*3=40,75359381
我该如何进行此操作?
作为我期望的输出
SKU stuff action acnumber year value
11202 8,85947691 3 137 2018 40,75359381
最佳答案
这是一个 tidyverse
解决方案:
df %>%
group_by(SKU,acnumber,year) %>%
summarize(value = 3*(median(stuff[action==1]) - median(stuff[match(1,action)-3:1])),
stuff=first(stuff),
action = sum(action)) %>%
select(SKU,stuff,action,acnumber,year,value)
# # A tibble: 1 x 6
# # Groups: SKU, acnumber [1]
# SKU stuff action acnumber year value
# <int> <dbl> <int> <int> <int> <dbl>
# 1 11202 8.86 3 137 2018 40.8
关于r - 如何在 R 中使用复杂条件减去中位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50815358/