簡體   English   中英

如何找到每個矩陣行的第一個值等於或大於預定義值的 position?

[英]How can I find the position of the first value of every matrixrow that equals or is greater than a pre-defined value?

我有一個數據矩陣,其中第 1 列由 plot 數字組成,列的 rest 由壓力數據組成,每列對應於某個土壤深度(從 1 到 80)。

我想找到每行中超過預定值(fe 3)的第一個值的 position(列號/列名)並將其存儲在向量中。

dataframe 看起來像這樣:

plot 1 2 3 4 5 6 7 …… 80
plot 1 0.5 1.5 1.6 1.7 2 3.2 3.6 ... 4
plot 2 0.8 1.4 1.8 2 2.6 2.9 3.2 ... 2.8
... ... ... ... ... ... ... ... ... ...

我嘗試將矩陣拆分為向量並使用 detect_index() 和 position(),但我似乎無法正確處理。

理想情況下,我會得到這樣的回報:

plot 深度
plot 1 6
plot 2 7
... ...

您可以使用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

df[-1]忽略第一列,將其與> 3進行比較給出邏輯值( TRUE / FALSE ),並且使用ties.method = 'first'我們確保選擇了第一個TRUE值。

也許你可以做這樣的事情:

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

運行此代碼會導致:

[[1]]
[1] 1 2 4

[[2]]
[1] 1 2 3 5

[[3]]
[1] 2 3 4 5

[[4]]
[1] 4 5

[[5]]
[1] 1 3 4 5

首先,我創建一個隨機的 5x5 矩陣,然后檢查每行的哪些位置超過某個值(在本例中 >0)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM