Reputation: 5
I have this matrix named d
.
This is the d
matrix
V1 V2 V3 V4
1 I 14.06863 11.50424 333173.1
2 N 14.50265 11.89501 387709.7
3 I 14.55234 11.95746 402124.0
4 I 14.78606 12.14149 453059.3
5 N 15.16970 12.51004 496142.1
6 D 14.41104 11.81296 539661.3
7 D 14.86976 12.23968 603475.4
I find the
d$Delta_Cost <- c(0, diff(d[, 4]))
d$Delta_LY <- c(0, diff(d[, 2]))
I need to loop through the matrix and remove the row that fulfills this condition
Delta_Cost>0 & Delta_LY<0
But i don't know how to do this in R.
Thank you!
Upvotes: 0
Views: 599
Reputation: 121057
Here's a reproducible version of your data:
d <- read.table(
text = "
V1 V2 V3 V4
1 I 14.06863 11.50424 333173.1
2 N 14.50265 11.89501 387709.7
3 I 14.55234 11.95746 402124.0
4 I 14.78606 12.14149 453059.3
5 N 15.16970 12.51004 496142.1
6 D 14.41104 11.81296 539661.3
7 D 14.86976 12.23968 603475.4",
header = TRUE
)
Since you want the contents of the loop to be run at least once, you want a repeat
loop rather han a while
loop. to_remove
is a logical vector which is TRUE
whenever you want to remove the row. If there are no rows to remove, if(!any(to_remove))
, we break out of the loop.
repeat
{
Delta_Cost <- c(0, diff(d[, 4]))
Delta_LY <- c(0, diff(d[, 2]))
to_remove <- Delta_Cost > 0 & Delta_LY < 0
if(!any(to_remove))
{
break
}
d <- d[!to_remove, ]
}
d
## V1 V2 V3 V4
## 1 I 14.06863 11.50424 333173.1
## 2 N 14.50265 11.89501 387709.7
## 3 I 14.55234 11.95746 402124.0
## 4 I 14.78606 12.14149 453059.3
## 5 N 15.16970 12.51004 496142.1
Upvotes: 1