Mike
Mike

Reputation: 1069

R:Finding rows which meet conditions

I've seen a few threads on this and have formulated a semi-answer, but what I require is slightly different from what I've seen. I'm looking to find the row BELOW a row which meets certain conditions. That is obviously a condition in and of itself, but I don't know how to formulate it in R. The code I have so far is:

index = decisionMatrix[,1] == 1 & decisionMatrix[,9] == 1  
decisionMatrix[index,7] = .01  

which assigns the value 0.01 to column 7 of rows that meet that condition. I would like to also make column 7 of the row below the selected rows = 0.1.

Any help would be greatly appreciated!
Thanks
Mike

Upvotes: 3

Views: 17094

Answers (2)

juba
juba

Reputation: 49033

Maybe with which ?

index <- which(decisionMatrix[,1] == 1 & decisionMatrix[,9] == 1)
## Shift indices by 1
index <- index+1
## Remove an index that would be greater than the number of rows
index <- index[index<=nrow(decisionMatrix)]
decisionMatrix[index,7] <- .01

EDIT : Following SimonO101 comment, if you want to modify both the rows matching conditions and the rows below, you just have to replace :

index <- index+1

By :

index <- c(index, index+1)

Upvotes: 8

Roland
Roland

Reputation: 132706

Subsetting in R uses logical vectors. That means you can shift the logical vector by one position. Example:

set.seed(42)
DF <- data.frame(x=1:10, y=rnorm(10))
#     x           y
# 1   1  1.37095845
# 2   2 -0.56469817
# 3   3  0.36312841
# 4   4  0.63286260
# 5   5  0.40426832
# 6   6 -0.10612452
# 7   7  1.51152200
# 8   8 -0.09465904
# 9   9  2.01842371
# 10 10 -0.06271410

ind <- DF$y < 0
#Shift by one position:
ind <- c(FALSE, head(ind,-1))
DF[ind,]
#  x         y
#3 3 0.3631284
#7 7 1.5115220
#9 9 2.0184237

Upvotes: 0

Related Questions