简体   繁体   English

在R中找到n-1个矩阵元素

[英]finding n-1 matrix elements in R

probably it's a very simple question with a very simple answer but I just can't figure it out by myself. 可能这是一个非常简单的问题,答案很简单,但我自己却无法解决。 I have a matrix called 'hz' with 1 column and 115 rows (hz[1:115, 1]) and I'm trying to find the values preceding those that are smaller than 1 and replace them. 我有一个名为'hz'的矩阵,具有1列和115行(hz [1:115,1]),并且试图查找小于1的值并将其替换。 I did the following: hz[c(hz < 1)] , got 11 values, then I tried to find the preceding ones: hz[c(hz < 1) - 1] , expected 11 values but got 114. If I try to find specific elements like hz[c(6, 26, 36)] , and the preceding ones: hz[c(6, 26, 36) - 1] I got 3 values in both cases as expected. 我执行了以下操作: hz[c(hz < 1)] ,得到11个值,然后尝试查找上述值: hz[c(hz < 1) - 1] ,期望11个值,但是得到114。如果尝试查找特定元素,例如hz[c(6, 26, 36)]和前面的元素: hz[c(6, 26, 36) - 1]在两种情况下我都得到了3个值,这与预期的一样。 So what's the difference? 那有什么区别呢? Is it a problem that I have a condition (<1) in the index? 我的索引中有条件(<1)是一个问题吗?

Thank you for your help! 谢谢您的帮助!

Viktor 维克多

Basically you want hz[which(hz < 1) - 1] . 基本上,您需要hz[which(hz < 1) - 1]

Note, hz < 1 is returning a logical vector, ie, TRUE / FALSE . 注意, hz < 1返回逻辑向量,即TRUE / FALSE If you take subtraction: (hz < 1) - 1 , TRUE will be seen as 1 and FALSE will be seen as 0 . 如果减去: (hz < 1) - 1 ,则TRUE将被视为1FALSE将被视为0 Applying which to a logical vector gives you positions (as integers) of TRUE , which is what you want. which应用于逻辑向量将使您的位置(作为整数)为TRUE ,这是您想要的。

Consider the following demonstration: 考虑以下演示:

x <- 1:5

x < 3
#[1]  TRUE  TRUE FALSE FALSE FALSE

(x < 3) - 1
#[1]  0  0 -1 -1 -1

which(x < 3)
#[1] 1 2

which(x < 3) - 1
#[1] 0 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM