简体   繁体   中英

R slickR package replace dosts with custom text

I have found cool carousel package for R https://cran.r-project.org/web/packages/slickR/vignettes/basics.html

following code will create carousel where dots are replaced by numbers

cP1 <- htmlwidgets::JS("function(slick,index) {
                            return '<a>'+(index+1)+'</a>';
                       }")

opts_dot_number <- settings(
  initialSlide = 0,
  slidesToShow = 5,
  slidesToScroll = 100,
  focusOnSelect = TRUE,
  dots = TRUE,
  customPaging = cP1
)

slick_dots <- slickR(
  obj = nba_player_logo$uri,
  height = 100,
  width = "95%"
)

slick_dots + opts_dot_number

My question is how would you replace numbers by custom text? Current code generates numbers from 1 to 11, but is it possible to replace it by

"one" "two" "three" etc

What you need is to add a function which translates numbers to words. There are plenty of those online, one can be found in this SO thread .

Then, it is as easy as adding this function to your custom JS:

cP1 <- htmlwidgets::JS("
function(slick,index) {
   const numToWordObj = {
     0: 'zero',
     1: 'one',
     2: 'two',
     3: 'three',
     4: 'four',
     5: 'five',
     6: 'six',
     7: 'seven',
     8: 'eight',
     9: 'nine',
     10: 'ten',
     11: 'eleven',
     12: 'twelve',
     13: 'thirteen',
     14: 'fourteen',
     15: 'fifteen',
     16: 'sixteen',
     17: 'seventeen',
     18: 'eighteen',
     19: 'nineteen',
     20: 'twenty',
     30: 'thirty',
     40: 'forty',
     50: 'fifty',
     60: 'sixty',
     70: 'seventy',
     80: 'eighty',
     90: 'ninety'
   };
   const placement = {
     100: ' hundred',
     1000: ' thousand',
     1000000: ' million',
     1000000000000: ' trillion'
   };
   
   const numToWord = (num) => {
     const limiter = (val) => num < val;
     const limiterIndex = Object.keys(placement).findIndex(limiter);
     const limiterKey = Object.keys(placement)[limiterIndex];
     const limiterVal = Object.values(placement)[limiterIndex - 1];
     const limiterMod = Object.keys(placement)[limiterIndex - 1];
   
     if (numToWordObj[num]) {
       return numToWordObj[num];
     }
     if (num < 100) {
       let whole = Math.floor(num / 10) * 10;
       let part = num % 10;
       return numToWordObj[whole] + ' ' + numToWordObj[part];
     }
   
     if (num < limiterKey) {
   
       let whole = Math.floor(num / limiterMod);
       let part = num % limiterMod;
       if (part === 0) {
         return numToWord(whole) + limiterVal;
       } else {
         return numToWord(whole) + limiterVal + ' and ' + numToWord(part);
       }
     }
   };
   return '<a>'+numToWord(index+1)+'</a>';   
}
")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM