R 中的滞后函数是否可以在不循环的情况下重复使用 R 中的计算值?
Can the lag function in R re-use calculated values in R without looping?
示例数据
set.seed(1)
library(tidyverse)
df1 <- data.frame(
Category = rep(c("Cat1","Cat2","Cat3"),3),
Value = c(sample(c(1:10),3), rep(NA, 6))
)
我正在尝试使用过去几年数据的滞后值来为数据框播种。这是问题的简化版本,但实际上,我需要做的是 lag
重新使用之前计算的滞后值。如果您 运行 下面的代码,第 4-6 行按照我的意图计算,但第 7-9 行仍然 NA
因为 lag
查看原始值,而不是新的计算值。我希望第 7-9 行也填充第 4-6 行的值。我知道我可以只写一个 for
循环来将值向前拉,但想看看是否有更像 R 的方法来完成这个。
df1 %>% group_by(Category) %>%
mutate(Value = ifelse(is.na(Value), lag(Value, 1), Value))
# Groups: Category [3]
Category Value
<fct> <int>
1 Cat1 9
2 Cat2 4
3 Cat3 7
4 Cat1 9
5 Cat2 4
6 Cat3 7
7 Cat1 NA
8 Cat2 NA
9 Cat3 NA
期望的结果
# A tibble: 9 x 2
# Groups: Category [3]
Category Value
<fct> <int>
1 Cat1 9
2 Cat2 4
3 Cat3 7
4 Cat1 9
5 Cat2 4
6 Cat3 7
7 Cat1 9
8 Cat2 4
9 Cat3 7
不确定这是否适用于您的问题,但您可以使用 fill
?
library(dplyr)
library(tidyr)
df1 %>%
group_by(Category) %>%
fill(Value, .direction = "down")
# A tibble: 9 x 2
# Groups: Category [3]
Category Value
<chr> <int>
1 Cat1 9
2 Cat2 4
3 Cat3 7
4 Cat1 9
5 Cat2 4
6 Cat3 7
7 Cat1 9
8 Cat2 4
9 Cat3 7
有了data.table
,我们可以在'Category'
分组后使用nafill
library(data.table)
setDT(df1)[, Value := nafill(Value, type = "locf"), Category]
df1
# Category Value
#1: Cat1 9
#2: Cat2 4
#3: Cat3 7
#4: Cat1 9
#5: Cat2 4
#6: Cat3 7
#7: Cat1 9
#8: Cat2 4
#9: Cat3 7
示例数据
set.seed(1)
library(tidyverse)
df1 <- data.frame(
Category = rep(c("Cat1","Cat2","Cat3"),3),
Value = c(sample(c(1:10),3), rep(NA, 6))
)
我正在尝试使用过去几年数据的滞后值来为数据框播种。这是问题的简化版本,但实际上,我需要做的是 lag
重新使用之前计算的滞后值。如果您 运行 下面的代码,第 4-6 行按照我的意图计算,但第 7-9 行仍然 NA
因为 lag
查看原始值,而不是新的计算值。我希望第 7-9 行也填充第 4-6 行的值。我知道我可以只写一个 for
循环来将值向前拉,但想看看是否有更像 R 的方法来完成这个。
df1 %>% group_by(Category) %>%
mutate(Value = ifelse(is.na(Value), lag(Value, 1), Value))
# Groups: Category [3]
Category Value
<fct> <int>
1 Cat1 9
2 Cat2 4
3 Cat3 7
4 Cat1 9
5 Cat2 4
6 Cat3 7
7 Cat1 NA
8 Cat2 NA
9 Cat3 NA
期望的结果
# A tibble: 9 x 2
# Groups: Category [3]
Category Value
<fct> <int>
1 Cat1 9
2 Cat2 4
3 Cat3 7
4 Cat1 9
5 Cat2 4
6 Cat3 7
7 Cat1 9
8 Cat2 4
9 Cat3 7
不确定这是否适用于您的问题,但您可以使用 fill
?
library(dplyr)
library(tidyr)
df1 %>%
group_by(Category) %>%
fill(Value, .direction = "down")
# A tibble: 9 x 2
# Groups: Category [3]
Category Value
<chr> <int>
1 Cat1 9
2 Cat2 4
3 Cat3 7
4 Cat1 9
5 Cat2 4
6 Cat3 7
7 Cat1 9
8 Cat2 4
9 Cat3 7
有了data.table
,我们可以在'Category'
nafill
library(data.table)
setDT(df1)[, Value := nafill(Value, type = "locf"), Category]
df1
# Category Value
#1: Cat1 9
#2: Cat2 4
#3: Cat3 7
#4: Cat1 9
#5: Cat2 4
#6: Cat3 7
#7: Cat1 9
#8: Cat2 4
#9: Cat3 7