编写一个程序,该程序从基数为10的数字x到基数为16的数字在R中 [英] Writing a program that goes from a number x in base 10 to a vector with the number in base 16 in R

查看:184
本文介绍了编写一个程序,该程序从基数为10的数字x到基数为16的数字在R中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(x)= {pre $ >十六进制1 < - 函数(x){
$ b $由< - 整数(0)

(r,10)16){
r< -x %% 16
x< -x%/%16
y< -c(r,y) {r < - A}
if(r == 11){r < - B}
if(r == 12){r < - C}
如果(r == 13){r < - D}
if(r == 14){r < - E}
if(r == 15){r < F}
}
y< - c(x,y)
y
}

我应该编写一个算法,在向量中以十六进制给出数字。我目前的算法实际上工作,但显示10,11,12,13,14,15,而不是A,B,C,D,E,F ...
任何想法如何使输出与这些字母而不是10,11 ...
预先感谢您的帮助。

解决方案

有一个R函数那已经这样做了:

 > prin_hex<  -  function(x)print(as.hexmode(x))
> prin_hex(30)
[1]1e
> print_hex< - function(x)print(paste(x,==,as.hexmode(x)))
> prin_hex(30)
[1]30 == 1e

您也可以离开类的数值 - hexmode print.hexmode 函数将返回一个字符值,同时让数字操作继续在这里执行。



(还有一个八进制八进制。)



print.hexmode(它指的是format.hexmode),我们发现,对于 print (通过格式
pre $ sp $ f $($%x $,< numeric> $)$ {$ c>)泛型为hexmode类正在完成b
$ b#eg
> sprintf(%x,20)
[1]14


hexadecimal1 <- function(x) {

y <- integer(0)

   while (x >= 16) {
   r <- x%%16
   x <- x%/%16
   y <- c(r, y)
   if(r==10) { r<- "A"}
   if(r==11) { r<- "B"}
   if(r==12) { r<- "C"}
   if(r==13) { r<- "D"}
   if(r==14) { r<- "E"}
   if(r==15) { r<- "F"}
   } 
y <- c(x, y)
y
}

I am supposed to write an algorithm that gives number in hexadecimal in a vector. My current algorithm actually works but displays 10,11,12,13,14,15 instead of A,B,C,D,E,F... Any idea how I can make the output be with those letters instead of 10, 11, ... Thank you in advance for your help.

解决方案

There's an R function that already does that:

> prin_hex <- function(x) print(as.hexmode(x))
> prin_hex(30)
[1] "1e"
> prin_hex <- function(x) print(paste(x, "==", as.hexmode(x)))
> prin_hex(30)
[1] "30 == 1e"

You could also leave a numeric value of class-hexmode and the print.hexmode function would return a character value while letting numeric operations continue to be performed on it.

(There's also an octmode for octal.)

After looking at the code for print.hexmode (which refers us to format.hexmode), we find that the heavy lifting for the print (by way of format) generics for the hexmode class is being done by

 sprintf("%x", <numeric>)

 # e.g.
> sprintf("%x", 20)
[1] "14"

这篇关于编写一个程序,该程序从基数为10的数字x到基数为16的数字在R中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆