2015-10-04 42 views
0

我有整數型的變量中,並具有值1/1整數值給出不同的值

> typeof(res[3,"V2.review/helpfulness"]) 
[1] "integer" 
> res[3,"V2.review/helpfulness"] 
[1] 1/1 

現在,當我存儲或將其轉換爲整數我想值作爲1分割1這是1 例如,如果我有2/3我想要的值0.6666 但它給我的結果作爲

> as.integer(res[3,"V2.review/helpfulness"]) 
[1] 6 
> as.double(res[3,"V2.review/helpfulness"]) 
[1] 6 

某人能否提供一個解決方案嗎?

+0

你可以顯示你的一些數據嗎?您可以將'dput(head(res))'的輸出複製粘貼到您的問題中。 – Heroka

+0

這是一個非常大的數據 –

+0

@Heroka你能明確你到底想知道什麼 –

回答

1

不,你正在尋找一個因素,而不是一個整數:

DF = data.frame(x = c("1/1","2/3")) 
typeof(DF$x) # "integer" 
class(DF$x) # "factor" 

瞭解存儲型(typeof)是很少重要。我建議閱讀R語言定義的前幾個部分,以加快R的課程和其他與您以前可能使用的語言區分的怪癖。要達到此目的,請鍵入help.start()並單擊「R語言定義」。


從文件讀取,R將字符串轉換爲因子,這些因子是分類變量。它不評估你在那裏的算術表達式(1/12/3),也沒有任何分數的類,只有整數,複數和浮點數。

如果你想存儲你的分數精確,單獨存放的分子和分母:

library(data.table) 
DF[,c("num","den")] <- tstrsplit(as.character(DF$x), "/", type.convert = TRUE) 

DF 
#  x num den 
# 1 1/1 1 1 
# 2 2/3 2 3 

到現在評估分數,你可以使用

DF$xnum <- DF$num/DF$den # obviously not an integer 

DF 
#  x num den  xnum 
# 1 1/1 1 1 1.0000000 
# 2 2/3 2 3 0.6666667 

要查看的所有類列,使用

sapply(DF, class) 
#   x  num  den  xnum 
# "factor" "integer" "integer" "numeric" 

評估分數的捷徑是DF$xnum <- sapply(as.character(DF$x), function(z) eval(parse(text=z))),但這種攻擊通常是強烈的不鼓勵。