[英]How do I use the command for for-loops?
I need to create the variable "peace" that tells me how many years there was peace before the variable conflict==1
(meaning a conflict starts).我需要创建变量“peace”,它告诉我在变量conflict==1
(意味着冲突开始)之前有多少年的和平。
Someone recommended to me to do a for
-loop with a variable ("peace") that starts with 0, adds 1 if conflict==0
, saves the value if conflict==1
and puts it back to 0 afterwards.推荐给我这样的人做for
一个变量(“和平”)-loop以0开始,加1,如果conflict==0
,保存值,如果conflict==1
,并将其返回到0之后。
Here is a short example of what the variable "peace" should look like:这是变量“peace”应该是什么样子的一个简短示例:
Df <- data.frame(country = c("A", "A", "A", "A", "A", "B","B", "B", "B"),
year = c("1950", "1951", "1952", "1953", "1954", "1950", "1951", "1952", "1953"),
conflict = c(0, 0, 1, 1, 0, 0, 1, 0, 1), peace = c(0, 0, 2, 2, 0, 0, 1, 0, 1))
What is the best way to achieve "peace"?实现“和平”的最佳方式是什么? How would the code look like?代码会是什么样子?
Thank you!谢谢!
See this link for your basic loops in R: https://www.geeksforgeeks.org/loops-in-r-for-while-repeat/有关 R 中的基本循环,请参阅此链接: https : //www.geeksforgeeks.org/loops-in-r-for-while-repeat/
For your issue, you would want to iterate over each row-index, except the first对于您的问题,您希望迭代每个行索引,除了第一个
# these two lines do two very different things. See if you can spot it.
peace <- 1
Df$peace <- 0
for (i in 2:nrow(Df)) {
# compare row i-1 to i
if (Df$country[i] != Df$country[i-1]) {
peace <- 1
next
}
if (Df$conflict[i] == 0 && Df$conflict[i-1] == 1) {
peace <- 1
} else if (Df$conflict[i] == 0) {
peace <- peace + 1
} else {
Df$peace[i] <- peace
}
}
I have created a new variable called n
as output -我创建了一个名为n
的新变量作为输出 -
library(dplyr)
Df <- Df %>% mutate(grp = data.table::rleid(conflict))
Df %>%
count(country, grp) %>%
group_by(country) %>%
mutate(n = lag(n, default = 0)) %>%
ungroup %>%
left_join(Df, by = c('country', 'grp')) %>%
mutate(n = replace(n, conflict == 0, 0))
# country grp n year conflict peace
# <chr> <int> <dbl> <chr> <dbl> <dbl>
#1 A 1 0 1950 0 0
#2 A 1 0 1951 0 0
#3 A 2 2 1952 1 2
#4 A 2 2 1953 1 2
#5 A 3 0 1954 0 0
#6 B 3 0 1950 0 0
#7 B 4 1 1951 1 1
#8 B 5 0 1952 0 0
#9 B 6 1 1953 1 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.