[英]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:
这显然是一个条件本身,但我不知道如何在R中制定它。我到目前为止的代码是:
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. 它将值0.01分配给满足该条件的行的第7列。 I would like to also make column 7 of the row below the selected rows = 0.1.
我还想在选定行= 0.1下面的行的第7列。
Any help would be greatly appreciated! 任何帮助将不胜感激!
Thanks 谢谢
Mike 麦克风
Maybe with which
? 也许与
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 : 编辑:关注SimonO101评论,如果你想修改符合条件的行和下面的行,你只需要替换:
index <- index+1
By : 通过:
index <- c(index, index+1)
Subsetting in R uses logical vectors. R中的子集使用逻辑向量。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.