I am trying to replace a sequence of rows based on the previous and next status in the rows. Let's say I have three factors namely 'Control', 'Fan' and 'Compressor' in a time-series data. If the factor 'Fan' appears between 'Control' and 'Compressor', then I wanted to change the factor 'Fan' to 'Compressor'.
For example, In the below table, I wanted to replace 'Fan' with 'Control'. Note: In the original, column 'Status' contained 'character'. I tried converting the characters to factors, thinking it might help solve the problem. So does not matter if the desired output is a character or factor.
| Status |
| ------------ |
| |
| Control |
| Control |
| Fan |
| Fan |
| Fan |
| Compressor |
| Compressor |
Desired output:
| Status |
| ------------ |
| |
| Control |
| Control |
| Compressor |
| Compressor |
| Compressor |
| Compressor |
| Compressor |
Thanks.
I tried the following,
for(i in 2:nrow(df))
df$Status[i]<- ifelse(df$Status[i]=='Fan' && df$Status[i+1]=='Compressor',
"Compressor",df$Status_change1[i])
But this only replaces the value in one row.
The output I got with the above code:
| Status |
| ------------ |
| |
| Control |
| Control |
| Fan |
| Fan |
| Compressor |
| Compressor |
| Compressor |
I am struck in finding the next time/episode when the status ' Compressor' occurs.
3条答案
按热度按时间os8fio9y1#
我认为使用游程编码可以稳健地处理这个问题。
zdwk9cvp2#
只是为了好玩,我认为这工程以及只是循环压缩机的位置,寻找元素之间的风扇和更换。伟大的答案以上。
gudnpqoy3#
或者与Tidyverse:
创建于2023年2月24日,使用reprex v2.0.2