在r中获得prop.table()

时间:2014-10-19 19:33:33

标签: r dataframe

我一直在尝试使用prop.table()来获取我拥有的数据比例,但不断出现错误。我的数据是......

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

感谢任何帮助或建议。

:)

1 个答案:

答案 0 :(得分: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的频率求和,

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 

然后在此prop.table对象上使用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
相关问题