[R] R for skip to the next row if condition met and then another condition to check
Adams, Jean
jvadams at usgs.gov
Tue Dec 6 22:24:44 CET 2016
This might help.
# your example data
trboot3 <- structure(c(0L, -1L, -1L, -1L, -1L, -1L, -1L, -1L, 0L, 0L, -1L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 0L, 0L, 0L, 0L,
1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, -1L, -1L, 0L, 1L, 0L, 0L, -1L,
-1L, -1L, -1L, -1L, -1L, -1L, -1L, -1L, 0L, 0L, 0L, 0L, 0L, 0L,
-1L, 0L, 0L, 0L), .Dim = c(20L, 3L), .Dimnames = list(NULL, c("V7",
"V8", "V9")))
# function to identify first occurrence of successive values in a vector
first <- function (x) {
l <- length(x)
y <- c(1, 1 - (x[-1] == x[-l]))
y==1
}
# start with a matrix of zeroes, the same size as the original
trboot4 <- array(0, dim=dim(trboot3), dimnames=dimnames(trboot3))
# identify the first occurrence of successive values in each column
indx <- apply(trboot3, 2, first)
# replace these first occurrence cells with their original values
trboot4[indx] <- trboot3[indx]
trboot4
V7 V8 V9
[1,] 0 1 0
[2,] -1 0 -1
[3,] 0 0 0
[4,] 0 0 0
[5,] 0 0 0
[6,] 0 0 0
[7,] 0 0 0
[8,] 0 1 0
[9,] 0 0 0
[10,] 0 0 0
[11,] -1 0 0
[12,] 0 0 0
[13,] 0 0 0
[14,] 0 0 0
[15,] 0 0 0
[16,] 0 -1 0
[17,] 0 0 -1
[18,] 0 0 0
[19,] 0 1 0
[20,] 0 0 0
Jean
On Sun, Dec 4, 2016 at 4:08 AM, Ashwini Patil <ash369ster at gmail.com> wrote:
> I have a dataset with many rows and columns. Below is a sample:
>
> V7 V8 V90 1 0-1 1 -1-1 1 -1-1 0 -1-1 0 -1-1 0
> -1-1 0 -1-1 1 -10 1 -10 1 -1-1 0 00 0 00 0 00
> 0 00 0 00 -1 00 -1 -10 0 00 1 00 0 0
>
> This data is saved in a matrix trboot3 What I want to do is create a loop
> whereby two conditions are checked and data is altered.
>
> 1. If there is a zero, skip to the next row.
> 2. If there is same number one below another in a row, keep the first
> number and change the rest to zero.
>
> Here is my code for the above loop:
>
> trboot4<-trboot3
> valboot<-length(trboot3[,1])for (k in 1:length(trboot3[1,])){
> for (i in 2:valboot-1){
> if (trboot3[k,i]==0) {i<-i+1}
> else{
> if(trboot3[k,i] == trboot3[k,i+1]){
> for (j in i+1:valboot){ if(trboot3[k,j] ==
> trboot3[k,i]){trboot4[k,j]<-0}else{break}
> if(j==valboot){break}
> }
> }
> }
> }}
>
> I want to save the new matrix in trboot4
>
> basically the above sample should become:
>
> V7 V8 V90 1 0-1 0 -10 0 00 0 00 0 00 0 00 0
> 00 1 00 0 00 0 0-1 0 00 0 00 0 00 0 00
> 0 00 -1 00 0 -10 0 00 1 00 0 0
>
>
> Thank you!
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/
> posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>
[[alternative HTML version deleted]]
More information about the R-help
mailing list