How to add increment/decrement indicator in R

Viewed 97

I have a datatable and want to add a decrement/increment indicator like an arrow up or down next to the value as a new column. Do you have any suggestions for this code example below? I have calculated the trend below and want to add something like an icon close to the value. When the value is bigger than x, arrow up; when value is smaller than 0, arrow down; when value is 0, then "-".

2 Answers

If you want a column of up and down arrows directly in the R console, you will need to use unicode symbols. Since your sample data consists mostly of NA values and doesn't allow all three arrow types to be drawn, I have modified the example to show how this might be achieved. The following code should be fully reproducible with copying and pasting into your console:

library(dplyr)

set.seed(3)

df1 <- data.frame(DATES = seq(as.Date("2020-11-20"), by = "month", length = 13),
                  TREND = round(runif(13, -10, 10)))

df1 %>% 
   mutate(CHANGE = ifelse(TREND < 0, "\u2193",
                          ifelse(TREND == 0, "\u2194", "\u2191"))) %>%
         as.matrix() %>% 
         noquote()

      DATES      TREND CHANGE
 [1,] 2020-11-20 -7    ↓     
 [2,] 2020-12-20  6    ↑     
 [3,] 2021-01-20 -2    ↓     
 [4,] 2021-02-20 -3    ↓     
 [5,] 2021-03-20  2    ↑     
 [6,] 2021-04-20  2    ↑     
 [7,] 2021-05-20 -8    ↓     
 [8,] 2021-06-20 -4    ↓     
 [9,] 2021-07-20  2    ↑     
[10,] 2021-08-20  3    ↑     
[11,] 2021-09-20  0    ↔     
[12,] 2021-10-20  0    ↔     
[13,] 2021-11-20  1    ↑   

Created on 2021-11-01 by the reprex package (v2.0.0)

Maybe you can try with sjPlot:

  library(sjPlot)
  df1 <- df1 %>% mutate(symbol = ifelse(TREND > 0, 
                       paste("<p>&#8593;</p>"),NA))
  
  sjPlot::tab_df(df1)
  
Related