数据样本。
mydat=structure(list(supplier = c("MyAgent", "MyAgent", "MyAgent",
"MyAgent", "S7", "S7", "S7", "S7", "S7", "Travelfusion", "Travelfusion",
"Travelfusion"), date = c("28.03.2021", "28.03.2021", "28.03.2021",
"28.03.2021", "25.03.2021", "25.03.2021", "25.03.2021", "25.03.2021",
"25.03.2021", "28.03.2021", "28.03.2021", "28.03.2021"), hour = c(3L,
4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 4L, 5L, 6L), weekday = c(0L,
0L, 0L, 0L, 4L, 4L, 4L, 4L, 4L, 0L, 0L, 0L), base_price = c(1944.7,
1949.43, 1954.16, 1958.89, 4595.2, 3170.02, 1744.84, 319.65,
-1105.53, 3.83, 3.49, 3.15)), class = "data.frame", row.names = c(NA,
-12L))
如何对于每个类别的supplier
变量,添加100,000
到每个类别的最新值。例如,S7
类别的最后一个值= -1105,53。所以-1105,53+100 000=98894,47
So98894,47
必须粘贴为最后一个值。但是最后一个Travelfusion
类别的值必须加上值 200 000。所以想要的输出
supplier date hour weekday base_price
1 MyAgent 28.03.2021 3 0 1944.70
2 MyAgent 28.03.2021 4 0 1949.43
3 MyAgent 28.03.2021 5 0 1954.16
4 MyAgent 28.03.2021 6 0 101958.89
5 S7 25.03.2021 7 4 4595.20
6 S7 25.03.2021 8 4 3170.02
7 S7 25.03.2021 9 4 1744.84
8 S7 25.03.2021 10 4 319.65
9 S7 25.03.2021 11 4 98894.47
10 Travelfusion 28.03.2021 4 0 3.83
11 Travelfusion 28.03.2021 5 0 3.49
12 Travelfusion 28.03.2021 6 0 200003.15
怎么做?
您可以在数据中添加一个新列以添加值并将其用于replace
:
library(dplyr)
value_to_add <- c(100000,100000, 200000)
mydat %>%
mutate(value_to_add = value_to_add[match(supplier, unique(supplier))]) %>%
group_by(supplier) %>%
mutate(base_price = replace(base_price, n(), last(base_price) + last(value_to_add))) %>%
ungroup %>%
select(-value_to_add)
# A tibble: 12 x 5
# supplier date hour weekday base_price
# <chr> <chr> <int> <int> <dbl>
# 1 MyAgent 28.03.2021 3 0 1945.
# 2 MyAgent 28.03.2021 4 0 1949.
# 3 MyAgent 28.03.2021 5 0 1954.
# 4 MyAgent 28.03.2021 6 0 101959.
# 5 S7 25.03.2021 7 4 4595.
# 6 S7 25.03.2021 8 4 3170.
# 7 S7 25.03.2021 9 4 1745.
# 8 S7 25.03.2021 10 4 320.
# 9 S7 25.03.2021 11 4 98894.
#10 Travelfusion 28.03.2021 4 0 3.83
#11 Travelfusion 28.03.2021 5 0 3.49
#12 Travelfusion 28.03.2021 6 0 200003.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句