I have a short matrix that represents in the below line:
a b
1 2
5 -6
-3 -4
4 3
I want to get x/max(x) for the positive value and x/min(x) for the negative value. the result column which wanted to obtain هt is as follows:
a.max b.max
1/5 2/3
5/5 -6/6
-3/3 -4/6
4/5 3/3
Note: To get the minimum, I have to make the number below the fraction positive
CodePudding user response:
How about this:
mat <- matrix(c(1,5,-3,4,2,-6,-4,3), ncol=2)
If you want it to do the division
apply(mat, 2, function(x)x/ifelse(x < 0, abs(min(x)), abs(max(x))))
#> [,1] [,2]
#> [1,] 0.2 0.6666667
#> [2,] 1.0 -1.0000000
#> [3,] -1.0 -0.6666667
#> [4,] 0.8 1.0000000
If you don't want it to do the math, if you want it to print the string.
apply(mat, 2, function(x)paste(x, "/", ifelse(x < 0, abs(min(x)), abs(max(x))), sep=""))
#> [,1] [,2]
#> [1,] "1/5" "2/3"
#> [2,] "5/5" "-6/6"
#> [3,] "-3/3" "-4/6"
#> [4,] "4/5" "3/3"
Created on 2022-12-08 by the reprex package (v2.0.1)
CodePudding user response:
Rewriting and slightly modifying @DaveArmstrong's solution using dplyr
, we can have this:
Data and Package
library(dplyr)
m <- tibble::tribble(
~a, ~b,
1, 2,
5, -6,
-3, -4,
4, 3
)
m
#> # A tibble: 4 × 2
#> a b
#> <dbl> <dbl>
#> 1 1 2
#> 2 5 -6
#> 3 -3 -4
#> 4 4 3
(1) Solution as number
m %>% mutate(across(a:b, ~.x/ifelse(.x < 0, abs(min(.x)), abs(max(.x)))))
#> # A tibble: 4 × 2
#> a b
#> <dbl> <dbl>
#> 1 0.2 0.667
#> 2 1 -1
#> 3 -1 -0.667
#> 4 0.8 1
(2) Solution as formula (character)
m %>% mutate(across(a:b, ~paste0(.x, "/", ifelse(.x < 0, abs(min(.x)), abs(max(.x))))))
#> # A tibble: 4 × 2
#> a b
#> <chr> <chr>
#> 1 1/5 2/3
#> 2 5/5 -6/6
#> 3 -3/3 -4/6
#> 4 4/5 3/3
Created on 2022-12-08 with reprex v2.0.2