计算每一行最大和最小列之间的差 [英] Calculate the difference between the largest and smallest column for each row

查看:40
本文介绍了计算每一行最大和最小列之间的差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题很简单-如何计算每一行的最大和最小列值之差?

The title is pretty straight forward - how can I calculate the difference between the largest and smallest value column-wise, for each row?

让我们假设这是我的数据:

Let's assume this is my data:

a b c d
1 2 3 4
0 3 6 9
3 2 1 4
9 8 7 6

对于每一行,我想找出两者之间的区别具有最高值的列和具有最低值的列-结果如下所示:

For each row, I want to find the difference between the column with the highest value and the column with the lowest value - the result looks like this:

3
9
3
3

任何帮助将不胜感激!

推荐答案

1

对于每一行(使用应用,其中 MARGIN = 1 ),使用 range 获得一个向量最小值和最大值,然后 diff 以获得这些值的差异

For each row (using apply with MARGIN = 1), use range to obtain a vector of the minimum and maximum value and then diff to obtain a difference of those values

apply(X = df, MARGIN = 1, function(x) diff(range(x)))
#[1] 3 9 3 3

2

如果想要更快的解决方案,则可以使用并行最大值和最小值( pmax pmin

If you want speedier solution, you can use parallel maxima and minima (pmax and pmin)

do.call(pmax, df) - do.call(pmin, df)
#[1] 3 9 3 3



数据

df = structure(list(a = c(1L, 0L, 3L, 9L), b = c(2L, 3L, 2L, 8L), 
    c = c(3L, 6L, 1L, 7L), d = c(4L, 9L, 4L, 6L)), .Names = c("a", 
"b", "c", "d"), class = "data.frame", row.names = c(NA, -4L))

时间

dat <- df[sample(1:4,5e6,replace=TRUE),]
rw <- seq_len(nrow(dat))

system.time({
    apply(X = dat, MARGIN = 1, function(x) diff(range(x)))
})
#STILL RUNNING...

system.time({
    rw <- seq_len(nrow(dat))
    dat[cbind(rw, max.col(dat))] - dat[cbind(rw, max.col(-dat))]
})
#   user  system elapsed 
#   3.48    0.11    3.59 

system.time(do.call(pmax, dat) - do.call(pmin, dat))
#   user  system elapsed 
#   0.23    0.00    0.26 

identical(do.call(pmax, dat) - do.call(pmin, dat),
      dat[cbind(rw, max.col(dat))] - dat[cbind(rw, max.col(-dat))])
#[1] TRUE

这篇关于计算每一行最大和最小列之间的差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆