[英]Increment variable based on specific string change in r
I am looking to create a variable that increments when specific strings appear in a column. 我正在寻找一个变量,当特定的字符串出现在列中时该变量递增。 If strings "x", "y", or "z" appear in Event, I want the sequence to increment, otherwise I would like it to stay constant.
如果字符串“ x”,“ y”或“ z”出现在事件中,则我希望序列递增,否则我希望它保持恒定。 Any help would be appreciated!
任何帮助,将不胜感激! See table below:
见下表:
Event Seq
1 a 1
2 b 1
3 x 2
4 c 2
5 a 2
6 b 2
7 y 3
8 a 3
9 z 4
10 b 4
11 y 5
12 a 5
13 b 5
This for
loop can update the Seq
as you requested in your question: 这个
for
循环可以按照您在问题中的要求更新Seq
:
for(i in 1:nrow(df)){
if(df$Event[i] %in% c('x','y','z')){
df$Seq[i] <- df$Seq[i] + 1
}
}
> df
Event Seq
1 a 1
2 b 1
3 x 3
4 c 2
5 a 2
6 b 2
7 y 4
8 a 3
9 z 5
10 b 4
11 y 6
12 a 5
13 b 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.