如何仅隔离R数据框架的最小级级值
我的问题
我有以下(简化的)dataFrame df
:
A B C
[1,] 2 -5 20
[2,] -10 -1 10
[3,] 10 -10 0
我想仅隔离最小幅度的值:
[ 2, -1, 0 ]
我该怎么做?
我尝试过的
到目前为止,我刚刚向我展示了最小值 absolute 值是每行:
MagMin <- vector()
for(i in 1:nrow(df)){
sub <- df[i,]
MagMin[i] <- min(abs(df[i,]))
}
它给我 [2,1, 0]
,但显然,我丢失了最小值的标牌。
I found a nice answer to the question in
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
演练:
当您想要Min- 幅度时,
min(abs(val))
将返回其阳性,您知道... < /p>我们可以使用
哪个min(abs(val))
要确定向量中的哪个是min- 幅度,它返回向量上的索引:使用它,我们可以基于最小数字提取特定值(POS或neg):
重复每行操作,我们使用
apply(mat,1,...)
。1
是margin = 1
,意思是“按行”,第三个参数(fun =
)是一个函数,它恰好采用一个函数争论并用它做点什么;在这种情况下,第一次被称为z
有效mat [1,]
,带有值c(2,-5,20);第二次,它有效地是
mat [2,]
,带有值c(-10,-1,10)
;等。数据
Walk-through:
When you want the min-magnitude,
min(abs(val))
will return the positive of that, which you know ...We can use
which.min(abs(val))
to determine which in the vector is the min-magnitude, which returns an index on the vector:Using that, we can extract the specific value (pos or neg) based on the min-magnitude:
to repeat the operation for each row, we use
apply(mat, 1, ...)
. The1
is forMARGIN=1
which means "by row", and the third argument (FUN=
) is a function that takes exactly one argument and does something with it; in this case, the first time it's called,z
is effectivelymat[1,]
, with the valuesc(2, -5, 20)
; the second time, it's effectivelymat[2,]
with valuesc(-10, -1, 10)
; etc.Data