Using data.table to Do Math: a Tiny Example

I am interested in the following problem: If

$$ x + y + z = 1, $$

where $x,\ y$ and $z$ are positive numbers, find the values of $x,\ y$ and $z$ such that

$$ \frac{x + y}{xyz} $$

attains its minimum. (Source: Quora post)

The Quora post gives an analytic solution; and here I will give it try using data.table package.

R code:

library(data.table)

# prepare data ------------------------------------------------------------
set.seed(12345)

N <- 1e5
dt <- data.table(z = runif(N))
dt[, x := runif(N, min = 0, max = 1 - z)]
dt[, y := 1 - x - z]
dt[, obj := (x + y) / (x * y * z)]


# find result -------------------------------------------------------------
dt[, min(obj)]
## [1] 16.00002
## find x, y and z -- method 1
dt[order(obj)][1]
##            z         x         y      obj
##        <num>     <num>     <num>    <num>
## 1: 0.5005866 0.2496991 0.2497143 16.00002
## find x, y and z -- method 2
setkey(dt, obj)[1]
## Key: <obj>
##            z         x         y      obj
##        <num>     <num>     <num>    <num>
## 1: 0.5005866 0.2496991 0.2497143 16.00002
## find x, y and z -- method 3
setkey(dt, NULL)
dt[which.min(obj)]
##            z         x         y      obj
##        <num>     <num>     <num>    <num>
## 1: 0.5005866 0.2496991 0.2497143 16.00002
Lingyun Zhang (张凌云)
Lingyun Zhang (张凌云)
Design Analyst

I have research interests in Statistics, applied probability and computation.