如果我有一个向量,我可以得到低于值的第一个出现:
test <- c(0.5,0.8,0.1,0.08,0.06,0.04)
which(test<0.1)[1]
Run Code Online (Sandbox Code Playgroud)
这正确地给出了答案4.但是,如何在矩阵的每列中首次出现,例如以下2列矩阵中的5次以下出现:
test2 <- matrix(c(5,8,3,4,7,5,6,2),ncol=2)
Run Code Online (Sandbox Code Playgroud)
使用applywith which返回一个列表:
> apply(test2<5,2,which)
[[1]]
[1] 3 4
[[2]]
[1] 4
Run Code Online (Sandbox Code Playgroud)
同时采用apply与which.min回报1所有列:
> apply(test2<5,2,which.min)
[1] 1 1
Run Code Online (Sandbox Code Playgroud)
然而,我想要的只是回归[1] 3 4- 我错过了一些明显的东西吗?
这是另一个答案.假设你的意思是test2你写test3,请注意'test2 <5'是一个逻辑向量.最小值为FALSE.最大值(TRUE)是您想要的:
> apply(test2<5,2,which.max)
[1] 3 4
Run Code Online (Sandbox Code Playgroud)
请注意,如果最大值不为TRUE,则这不正确.
试试这个:
test2 <- matrix(c(5,8,3,4,7,5,6,2),ncol=2)
> test2
[,1] [,2]
[1,] 5 7
[2,] 8 5
[3,] 3 6
[4,] 4 2
> foo <- function(x){which(x < 5)[1]}
> apply(test2,2,foo)
Run Code Online (Sandbox Code Playgroud)
这里的关键是你把你知道的作品放在一个矢量上,然后简单地将它包装在一个函数中.apply好吧,将该功能应用于每一列.