Home > Blockchain >  How to add increment/decrement indicator in R
How to add increment/decrement indicator in R

Time:11-01

I have a datatable an want to add a decrement/increment indicator like a 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 smth like an icon close to the value. When the value is bigger then x arrow up, when value is smaller then 0 arrow down, when value equal to 0 then "-".

library(readr)
library(dplyr)
library(tidyverse)

df1 <- data.frame(DATES = c("2020/11/20", "2020/12/20", "2021/01/20", "2021/02/20", "2021/03/20", "2021/04/20",
                            "2021/05/20", "2021/06/20", "2021/07/20", "2021/08/20", "2021/09/20", "2021/10/20",
                            "2021/11/20"),
                  UTILIZATION = round(c(0.00, 0.00, 0.00015, 0.00, 0.00, 0.00010, 0.005, 0.001, 0.00, 0.323, 0.4427, 0.00, 0.00),digits=2))
          
df1$TREND <- sapply(1:nrow(df1),
                    function(i) {
                      if (i-12 > 0) mean(df1$UTILIZATION[i-1:2]) / mean(df1$UTILIZATION[i-3:12]) 
                      else NA_real_
                    } )


result <- df1[13, ]
result1<-result %>% select(TREND)
result1$TREND <- result1$TREND %% 1
result1

CodePudding user response:

Maybe you can try with sjPlot:

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

CodePudding user response:

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)

  • Related