我正在寻找一种tidyverse解决方案,通过迭代向量,根据某种条件填充列.
Column prev
represents previous state of a system, new
represents the new state. prev
and new
are always in sequence, but some of them may loop, like in the example below.
0
and 100
values are start and finish states, the states represented here as letters are the important ones.
对于prev
和new
的特定组合(即,同时满足prev_condition
和new_condition
),我需要迭代一个更大的向量vec
(它的元素比可能的状态组合多),并将值按顺序放入第to_do
列
我想补充一点,prev
和new
的组合不需要是唯一的,这就是为什么我添加了第change
列来指示发生的每个状态更改.
这里是一个简单的例子和一个解决方案在基地R.我真的希望一个优雅的tidyverse解决方案.非常感谢.
# Minimal reproducible data
df <- data.frame(prev = c("0", rep(letters[1:3], 2), rep(letters[4:10], 3)),
new = c(rep(letters[1:3], 2), rep(letters[4:10], 3), "100"),
change = 1:28,
to_do = rep(NA, 28))
# Vector for iteration
vec <- 1:30
# Conditions
prev_condition <- c(letters[4:6]) # prev state must be any of: "d" "e" "f"
new_condition <- c(letters[5:7]) # new state must be any of: "e" "f" "g"
# base R solution
n_row <- length(df[df$prev %in% prev_condition & df$new %in% new_condition, "to_do"])
df[df$prev %in% prev_condition & df$new %in% new_condition, "to_do"] <- vec[1:n_row]
df
#> prev new change to_do
#> 1 0 a 1 <NA>
#> 2 a b 2 <NA>
#> 3 b c 3 <NA>
#> 4 c a 4 <NA>
#> 5 a b 5 <NA>
#> 6 b c 6 <NA>
#> 7 c d 7 <NA>
#> 8 d e 8 I
#> 9 e f 9 Y
#> 10 f g 10 N
#> 11 g h 11 <NA>
#> 12 h i 12 <NA>
#> 13 i j 13 <NA>
#> 14 j d 14 <NA>
#> 15 d e 15 W
#> 16 e f 16 Q
#> 17 f g 17 Z
#> 18 g h 18 <NA>
#> 19 h i 19 <NA>
#> 20 i j 20 <NA>
#> 21 j d 21 <NA>
#> 22 d e 22 V
#> 23 e f 23 C
#> 24 f g 24 C
#> 25 g h 25 <NA>
#> 26 h i 26 <NA>
#> 27 i j 27 <NA>
#> 28 j 100 28 <NA>
由reprex package(v2.0.1)于2022-05-09创建