2014-10-19 29 views
-1

我一直在嘗試使用prop.table()來獲取我擁有的數據比例,但不斷收到錯誤。我的數據是..prop.table()error

Letter Total 
a  10 
b  34 
c  8 
d  21 
.  . 
.  . 
.  . 
z  2 

我想要第三列給出每個字母的比例。 我的原始數據是在數據幀,所以我已經試過轉換爲數據表,然後使用prop.table ..

testtable = table(lettersdf) 
prop.table(testtable) 

當我嘗試這個,我不斷收到錯誤,

Error in margin.table(x, margin) : 'x' is not an array 

任何幫助或建議表示讚賞。

:)

+2

嘗試'lettersdf $ prop < - prop.table(lettersdf [,2])''。 – jbaums 2014-10-19 19:45:48

+1

我無法重現您的錯誤。 class(lettersdf)'的結果是什麼? – 2014-10-19 19:46:22

+1

請爲我們提供一個自包含的R代碼來解決此問題。 – 2014-10-19 19:51:03

回答

2

如果您的數據Letter列沒有重複的值,這樣

Df <- data.frame(
    Letter=letters, 
    Total=sample(1:50,26), 
    stringsAsFactors=F) 

你可以做到這一點,而不是使用prop.table

Df$Prop <- Df$Total/sum(Df$Total) 
> head(Df) 
    Letter Total  Prop 
1  a 45 0.074875208 
2  b  1 0.001663894 
3  c 13 0.021630616 
4  d 15 0.024958403 
5  e 24 0.039933444 
6  f 39 0.064891847 
> sum(Df[,3]) 
[1] 1 

如果有重複的值,如在此對象中

Df2 <- data.frame(
    Letter=sample(letters,50,replace=T), 
    Total=sample(1:50,50), 
    stringsAsFactors=F) 

你可以做一個table總結的獨特Letter S中的頻率,

Table <- table(rep(Df2$Letter,Df2$Total)) 
> Table 
    a b c d e f h j k l m n o p q t v w x y z 
48 16 99 2 40 75 45 42 66 6 62 27 88 99 32 96 85 64 53 161 69 

,然後這個table對象使用prop.table

> prop.table(Table) 
      a   b   c   d   e   f   h   j   k   l   m 
0.037647059 0.012549020 0.077647059 0.001568627 0.031372549 0.058823529 0.035294118 0.032941176 0.051764706 0.004705882 0.048627451 
      n   o   p   q   t   v   w   x   y   z 
0.021176471 0.069019608 0.077647059 0.025098039 0.075294118 0.066666667 0.050196078 0.041568627 0.126274510 0.054117647 

你也可以製作成data.frame這樣的:

Df2.table <- cbind(
    data.frame(Table,stringsAsFactors=F), 
    Prop=as.numeric(prop.table(Table))) 
> head(Df2.table) 
    Var1 Freq  Prop 
1 a 48 0.037647059 
2 b 16 0.012549020 
3 c 99 0.077647059 
4 d 2 0.001568627 
5 e 40 0.031372549 
6 f 75 0.058823529