Home > Back-end >  Highlight values in a data frame in R
Highlight values in a data frame in R

Time:03-08

I have a database with rankings from three different methods. Note that some methods have similar values, for example for the first alternative we have two values equal to 1 and another with a value equal to 29. Therefore, I would like to know if there is any way to highlight the repeated values for the same line, who knows how to leave it in red or in another way of highlighting.

Can you help me with this?

result<-structure(list(n = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 
         12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 
         28, 29), M1 = c(29L, 1L, 28L, 27L, 25L, 26L, 24L, 20L, 21L, 
         22L, 23L, 15L, 12L, 17L, 18L, 19L, 16L, 13L, 14L, 5L, 6L, 7L, 
         8L, 9L, 10L, 11L, 4L, 2L, 3L), M2 = c(1, 29, 28, 27, 26, 25, 
        24, 23, 22, 21, 20, 15, 12, 19, 18, 17, 16, 14, 13, 11, 10, 9, 
       8, 7, 6, 5, 4, 3, 2), M3 = c(1L, 29L, 28L, 27L, 25L, 26L, 24L, 
       20L, 21L, 22L, 23L, 15L, 12L, 17L, 18L, 19L, 16L, 13L, 14L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 4L, 2L, 3L)), class = "data.frame", row.names = c(NA,-29L))

> result
    n M1 M2 M3
1   1 29  1  1
2   2  1 29 29
3   3 28 28 28
4   4 27 27 27
5   5 25 26 25
6   6 26 25 26
7   7 24 24 24
8   8 20 23 20
9   9 21 22 21
10 10 22 21 22
11 11 23 20 23
12 12 15 15 15
13 13 12 12 12
14 14 17 19 17
15 15 18 18 18
16 16 19 17 19
17 17 16 16 16
18 18 13 14 13
19 19 14 13 14
20 20  5 11  5
21 21  6 10  6
22 22  7  9  7
23 23  8  8  8
24 24  9  7  9
25 25 10  6 10
26 26 11  5 11
27 27  4  4  4
28 28  2  3  2
29 29  3  2  3

CodePudding user response:

Colors are only available in the RStudio console through the crayon package, so you would need to write a whole custom print method, which is a fair bit of work. Instead, you could use the tidyverse packages to create a set of flag columns that make it easier to track the duplications:

library(tidyverse)

output <- result %>%
  pivot_longer(M1:M3) %>% 
  group_by(n, value) %>% 
  mutate(T_F = ifelse(n() > 1, 'T', 'F')) %>% 
  pivot_wider(values_from = c(value, T_F), names_glue = '{name}_{.value}')

colnames(output) <- gsub('_value', '', colnames(output))

       n    M1    M2    M3 M1_T_F M2_T_F M3_T_F
   <dbl> <dbl> <dbl> <dbl> <chr>  <chr>  <chr> 
 1     1    29     1     1 F      T      T     
 2     2     1    29    29 F      T      T     
 3     3    28    28    28 T      T      T     
 4     4    27    27    27 T      T      T     
 5     5    25    26    25 T      F      T     
 6     6    26    25    26 T      F      T     
 7     7    24    24    24 T      T      T     
 8     8    20    23    20 T      F      T     
 9     9    21    22    21 T      F      T     
10    10    22    21    22 T      F      T     
# … with 19 more rows 
  •  Tags:  
  • r
  • Related