r - Determine the max values in one column based on another column -
i determine max values in column value1
based values in column value2
:
df <- 'inf value1 value2 xx1 20 30 xx2 15 40 xx3 25 20' df <- read.table(text=df, header=t)
my expected output that:
out <- 'inf value1 value2 xx1 20 30 xx2 15 40 xx3 20 20' out <- read.table(text=out, header=t)
in third row in column value2
have 20
instead 25
, because value @ value2
column @ same row. have large dataset, appreciate ideas deal that.
you find min
value per row using pmin
with(df, pmin(value1, value2)) ## [1] 20 15 20
some benchmarks
set.seed(123) test1 <- sample(1e3, 1e8, replace = true) test2 <- sample(1e3, 1e8, replace = true) ### solution system.time(res1 <- pmin(test1, test2)) # user system elapsed # 2.87 0.11 3.00 ### @avinash system.time(res2 <- ifelse(test1 < test2, test1, test2)) # user system elapsed # 16.33 2.41 18.87 ### contributed @colonel system.time({temp <- test1 > test2 ; test1[temp] <- test2[temp]}) # user system elapsed # 2.34 0.29 2.63 identical(res1, res2) # [1] true identical(res1, test1) # [1] true
Comments
Post a Comment