0

I have a frame in which various numeric values are written, it looks like this:

library(data.table)
set.seed(1)
x <- data.table(a = runif(n = 5, min = -4, max = 4), b = runif(n = 5, min = -4, max = 4), c = runif(n = 5, min = -4, max = 4),
                d = runif(n = 5, min = -4, max = 4), e = runif(n = 5, min = -4, max = 4), f = runif(n = 5, min = -4, max = 4),
                g = runif(n = 5, min = -4, max = 4))
> x
            a          b          c            d          e          f          g
1: -2.8546673  2.7070725  0.3029194 -0.142643414  0.8779915 -3.0102115 -2.6380514
2: -1.2441009  3.0354664 -3.1595989  3.364142725 -1.8860076 -3.4397386 -3.5664766
3: -0.7538913  3.4856997  2.4135016 -3.667772569 -0.6152111  3.7145363  1.2626246
4: -3.3175120 -3.4203149  1.9171340 -1.648065608 -1.0674911 -0.4599191  0.6252953
5:  3.4605754 -0.9699245 -3.5828079  0.006803898  3.5400426 -1.0378210  3.8968141

I need to find line by line the two highest values and the two lowest values and write the name of the column that contains this value to the table. I will give an example of how it should look on one line:

           a        b         c          d         e         f         g max1 max2 min1 min2
1: -2.854667 2.707073 0.3029194 -0.1426434 0.8779915 -3.010211 -2.638051    b    e    f    a

It is also worth noting that in the future I will have frames of different lengths, so a solution is required independent of the length of the frame, I also need the ability to change the number of highest and lowest values, for example, three largest and three smallest or one largest and one least. UPDATE: I have a solution for finding the maximum and minimum values, it does not give the name of the column, but its index, which is also acceptable, any way of solving the question is acceptable

q <- NULL
for (i in 1:nrow(x)) {
  temp <- data.table(x[i, ], max = which.max(x[i,]), min = which.min(x[i,]))
  q <- rbind(q, temp)
}
q
  • 1
    What did you try? What step are you having trouble with? And as a suggestion: Maybe you could break the problem down to include only one question at a time (i.e. the calculation of the new columns, only then try to figure out how to pass number of values etc. after you tried for yourself to find a solution.... – dario Oct 19 '21 at 08:42
  • Do you need a `data.table` solution (by using the `data.table` syntax) or are other solutions (for example a `tidyverse`-solution) sufficient? – Martin Gal Oct 19 '21 at 08:44
  • Is it possible to traspose the dataframe or could be problematic? – domiziano Oct 19 '21 at 08:45

0 Answers0