2013-10-21 106 views
15

我發現在fBasics包中有函數.hex.to.dec在R中將十六進制轉換爲十進制

當我做.hex.to.dec(a),它的工作原理。

我有一個數據幀與由這樣的值的列samp_column

a373, 115c6, a373, 115c6, 176b3 

當我做.hex.to.dec(samp_column),我得到這個錯誤:

"Error in nchar(b) : 'nchar()' requires a character vector"

當我做.hex.to.dec(as.character(samp_column)),我得到這個錯誤:

"Error in rep(base.out, 1 + ceiling(log(max(number), base = base.out))) : invalid 'times' argument"

什麼是be這樣做的方式?

+1

'strtoi'將執行此操作。或者很長的路要走:'Rutils :: as.character.binmode',然後用'as.numeric'將字符轉換爲數字:-) –

+3

請閱讀[如何格式化您的問題](http://stackoverflow.com/editing-help),然後介紹包含數據的[如何製作可重複使用的示例](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)。 – Thomas

+0

謝謝卡爾!出於某種原因,這個功能沒有出現在我的Google搜索中,但它似乎工作得很好。 :)乾杯! –

回答

24

使用base::strtoi轉換十六進制字符矢量爲整數:

strtoi(c("0xff", "077", "123")) 
#[1] 255 63 123 
+5

通過數字庫進行轉換是可能難以找到正確幫助頁面的任務之一。轉換功能遍佈各地,名字各異。另見'?hexmode','?as.hexmode'和'?octmode' –

+0

好的,*現在*誰發佈簡短的答案? :-)。 PS thx爲彈球的讚譽。 –

+0

@CarlWitthoft ha!好的,指出。我更願意將此視爲一個最小可行的例子,但正如你所說,這是一個精細的彈球嚮導。 :-) –

8

有轉換六角<簡單和通用的方法 - >使用 「C/C++方法」 其他格式:

V <- c(0xa373, 0x115c6, 0xa373, 0x115c6, 0x176b3) 

sprintf("%d", V) 
#[1] "41843" "71110" "41843" "71110" "95923" 

sprintf("%.2f", V) 
#[1] "41843.00" "71110.00" "41843.00" "71110.00" "95923.00" 

sprintf("%x", V) 
#[1] "a373" "115c6" "a373" "115c6" "176b3" 
1

strtoi()具有31位的限制。高位設置的十六進制數返回NA

> strtoi('0x7f8cff8b') 
[1] 2139946891 
> strtoi('0x8f8cff8b') 
[1] NA 
+0

這應該是對接受答案的評論。 – NoBackingDown

相關問題