在R中获取prop.table() [英] Getting a prop.table() in r
问题描述
我一直在尝试使用prop.table()来获取我拥有的数据的比例,但是一直在出错.我的数据是..
I've been trying to use prop.table() to get the proportions of data I have but keep getting errors. My data is..
Letter Total
a 10
b 34
c 8
d 21
. .
. .
. .
z 2
我想要第三列给出每个字母的比例.我的原始数据在数据框中,因此我尝试转换为数据表,然后使用prop.table ..
I want a third column that gives the proportion of each letter. My original data is in a data frame so I've tried converting to a data table and then using prop.table ..
testtable = table(lettersdf)
prop.table(testtable)
尝试此操作时,我不断收到错误消息,
When I try this I keep getting the error,
Error in margin.table(x, margin) : 'x' is not an array
任何帮助或建议都将受到赞赏.
Any help or advise is appreciated.
:)
推荐答案
如果数据中的 Letter
列没有重复的值,例如
If the Letter
column in your data does not have duplicate values, like this
Df <- data.frame(
Letter=letters,
Total=sample(1:50,26),
stringsAsFactors=F)
您可以执行此操作,而不是使用 prop.table
:
you can just do this instead of using 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
如果存在重复的值,例如该对象中的
If there are duplicated values, like in this object
Df2 <- data.frame(
Letter=sample(letters,50,replace=T),
Total=sample(1:50,50),
stringsAsFactors=F)
您可以制作一个 table
来汇总唯一的 Letter
s
you can make a table
to sum the frequency of unique 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
:
and then use prop.table
on this table
object:
> 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
这篇关于在R中获取prop.table()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!