# Simplify and make the if statement more efficient?

Good practice to provide data with a `reprex`. (See the FAQ).

When in doubt, abstract away the common elements.

When modifying all-numeric data, take advantage of matrix algebra.

``````trim_to <- function(x,y) {
wide = dim(x)[1]
long = dim(x)[2]
size = wide * long
m = as.matrix(x,nrow = wide)
n = matrix(rep(y,size),nrow = wide)
m[which(m > n)] = 1
return(m)
}

d <- data.frame(
lazy_a = c(0.24, 0.66, 0.09, 0.08, 0.9, 0.18,0.88, 0.19),
lazy_b = c(0.13, 0.51, 0.5, 0.92, 0.21, 0.59, 0.24,0.13),
lazy_c = c(0.22, 0.42, 0.51, 0.61, 0.1, 0.99, 0.77, 0.65),
lazy_d = c(0.18, 0.47, 0.44, 0.8, 0.03, 0.58, 0.01, 0.86),
lazy_e = c(0.77, 0.69, 0.97, 0.95, 0.06, 0.25, 0.82, 0.57),
lazy_f = c(0.83, 0.75, 0.63, 0.08, 0.96, 0.09, 0.66, 0.41),
lazy_g = c(0.9, 0.54, 0.27, 0.97, 0.13, 0.21, 0.86, 0.1),
lazy_h = c(0.59, 0.74, 0.25, 0.84, 0.57, 0.44, 0.27, 0.4))

d
#>   lazy_a lazy_b lazy_c lazy_d lazy_e lazy_f lazy_g lazy_h
#> 1   0.24   0.13   0.22   0.18   0.77   0.83   0.90   0.59
#> 2   0.66   0.51   0.42   0.47   0.69   0.75   0.54   0.74
#> 3   0.09   0.50   0.51   0.44   0.97   0.63   0.27   0.25
#> 4   0.08   0.92   0.61   0.80   0.95   0.08   0.97   0.84
#> 5   0.90   0.21   0.10   0.03   0.06   0.96   0.13   0.57
#> 6   0.18   0.59   0.99   0.58   0.25   0.09   0.21   0.44
#> 7   0.88   0.24   0.77   0.01   0.82   0.66   0.86   0.27
#> 8   0.19   0.13   0.65   0.86   0.57   0.41   0.10   0.40
(d <- trim_to(d,0.75))
#>      lazy_a lazy_b lazy_c lazy_d lazy_e lazy_f lazy_g lazy_h
#> [1,]   0.24   0.13   0.22   0.18   1.00   1.00   1.00   0.59
#> [2,]   0.66   0.51   0.42   0.47   0.69   0.75   0.54   0.74
#> [3,]   0.09   0.50   0.51   0.44   1.00   0.63   0.27   0.25
#> [4,]   0.08   1.00   0.61   1.00   1.00   0.08   1.00   1.00
#> [5,]   1.00   0.21   0.10   0.03   0.06   1.00   0.13   0.57
#> [6,]   0.18   0.59   1.00   0.58   0.25   0.09   0.21   0.44
#> [7,]   1.00   0.24   1.00   0.01   1.00   0.66   1.00   0.27
#> [8,]   0.19   0.13   0.65   1.00   0.57   0.41   0.10   0.40
``````

Created on 2023-03-28 with reprex v2.0.2

1 Like