[英]Alternative for nested for loop in R
I am trying to achieve a result in R as follows: I have a dataset, like below我正在尝试在 R 中实现如下结果:我有一个数据集,如下所示
and I'm trying to achieve result as follows:我试图达到如下结果:
Conditions are:条件是:
Constraints: Do not want to use nested for loops.约束:不想使用嵌套的 for 循环。 Is there a better way to achieve the result in R.
有没有更好的方法来实现 R 中的结果。
Thank you in advance for the suggestions/solutions.提前感谢您的建议/解决方案。
It's much easier to help if your data is reproducible.如果您的数据是可重现的,那么提供帮助会容易得多。 The data in the images doesn't have column names, but the following code reproduces the data frame and names the columns
col1
, col2
and col3
:图像中的数据没有列名,但以下代码再现了数据框并命名了列
col1
、 col2
和col3
:
df <- data.frame(col1 = rep(1:17, 2),
col2 = rep(c("A", "B"), each = 17),
col3 = rep(rep(c(FALSE, TRUE), 4),
times = c(2, 10, 3, 4, 5, 3, 3, 4)))
To do what you need, we can group the data according to each run of TRUE or FALSE in column 3 using rleid
from data.table
, then insert a rev
erse integer seq
uence for the FALSE segments.为了满足您的需要,我们可以使用
rleid
中的data.table
根据第 3 列中每次运行的 TRUE 或 FALSE 对数据进行分组,然后为 FALSE 段插入rev
seq
。 Finally, ungroup
, then shift the new column up one position using lead
.最后,
ungroup
,然后使用lead
将新列向上移动一个 position。
library(tidyverse)
df <- df %>%
group_by(grp = data.table::rleid(col3)) %>%
mutate(col4 = rev(seq(n())) * (1 - col3)) %>%
group_by(col2) %>%
mutate(col4 = lead(col4, default = 0)) %>%
select(-grp)
The result matches your expected output:结果与您预期的 output 匹配:
print(df, n = 34)
#> # A tibble: 34 x 4
#> col1 col2 col3 col4
#> <int> <chr> <lgl> <dbl>
#> 1 1 A FALSE 1
#> 2 2 A FALSE 0
#> 3 3 A TRUE 0
#> 4 4 A TRUE 0
#> 5 5 A TRUE 0
#> 6 6 A TRUE 0
#> 7 7 A TRUE 0
#> 8 8 A TRUE 0
#> 9 9 A TRUE 0
#> 10 10 A TRUE 0
#> 11 11 A TRUE 0
#> 12 12 A TRUE 3
#> 13 13 A FALSE 2
#> 14 14 A FALSE 1
#> 15 15 A FALSE 0
#> 16 16 A TRUE 0
#> 17 17 A TRUE 0
#> 18 1 B TRUE 0
#> 19 2 B TRUE 5
#> 20 3 B FALSE 4
#> 21 4 B FALSE 3
#> 22 5 B FALSE 2
#> 23 6 B FALSE 1
#> 24 7 B FALSE 0
#> 25 8 B TRUE 0
#> 26 9 B TRUE 0
#> 27 10 B TRUE 3
#> 28 11 B FALSE 2
#> 29 12 B FALSE 1
#> 30 13 B FALSE 0
#> 31 14 B TRUE 0
#> 32 15 B TRUE 0
#> 33 16 B TRUE 0
#> 34 17 B TRUE 0
Created on 2022-09-07 with reprex v2.0.2使用reprex v2.0.2创建于 2022-09-07
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.