R 如何找到每个矩阵行中等于或大于预定义值的第一个值的位置?

R 如何找到每个矩阵行中等于或大于预定义值的第一个值的位置?,r,matrix,position,R,Matrix,Position,我有一个数据矩阵,其中第1列由图号组成,其余列由压力数据组成,每列对应于特定的土壤深度(从1到80) 我想找到每行中第一个超过预定值(f.e.3)的值的位置(columnnumber/columnname),并将其存储在向量中 数据帧的外观如下所示: M<-matrix(rnorm(25),nrow=5) apply(M,1,function(x) which(x>0)) 情节 1. 2. 3. 4. 5. 6. 7. .... 80 地块1 0.5 1.5 1.6 1.7 2.

我有一个数据矩阵,其中第1列由图号组成,其余列由压力数据组成,每列对应于特定的土壤深度(从1到80)

我想找到每行中第一个超过预定值(f.e.3)的值的位置(columnnumber/columnname),并将其存储在向量中

数据帧的外观如下所示:

M<-matrix(rnorm(25),nrow=5)
apply(M,1,function(x) which(x>0))
情节 1. 2. 3. 4. 5. 6. 7. .... 80 地块1 0.5 1.5 1.6 1.7 2. 3.2 3.6 ... 4. 情节2 0.8 1.4 1.8 2. 2.6 2.9 3.2 ... 2.8 ... ... ... ... ... ... ... ... ... ...
您可以使用
max.col

result <- data.frame(plot = df$plot, depth = max.col(df[-1] > 3, ties.method = 'first'))
result

#    plot depth
#1 plot 1     6
#2 plot 2     7
result 3,ties.method='first'))
结果
#绘图深度
#1地块16
#2地块2 7

df[-1]
忽略第1列,将其与
>3
进行比较,给出逻辑值(
TRUE
/
FALSE
),并使用
ties.method='first'
确保选择了第1列
TRUE
值。

也许您可以这样做:

M<-matrix(rnorm(25),nrow=5)
apply(M,1,function(x) which(x>0))

首先,我创建一个随机的5x5矩阵,然后检查每行的哪些位置超过某个值(在本例中大于0)。

欢迎使用堆栈溢出。请通过粘贴数据样本使问题重现:使用
dput(head(your_data_sample,n))
其中
n
足够证明问题。这使得其他人更容易测试和验证解决方案。我会使用[
tidyr::gather
]将所有列转换为长格式-除了plot one(),然后是值