简体   繁体   English

计算R中两个离散变量的概率

[英]Calculate probability for two discrete variables in R

So, I have something like: 所以,我有这样的事情:

V1 V2
X  B
Y  A
X  A
Y  B
X  B
X  B

And I need: 我需要:

    A     B
X  0.17  0.5
Y  0.17  0.17

*Note: They do not sum up to 1 because I round 1.666 to 1.7.* *注意:它们之和不等于1,因为我将1.666舍入为1.7.*

Use the table function to create tables of counts: 使用table函数创建计数表:

> table(df)
   V2
V1  A B
  X 1 3
  Y 1 1

The table of probabilities is derived from this in a straightforward way: 概率表是从中直接得出的:

> table(df) / nrow(df)
   V2
V1          A         B
  X 0.1666667 0.5000000
  Y 0.1666667 0.1666667

Or, alternatively, using prop.table : 或者,使用prop.table

> prop.table(table(df))
   V2
V1          A         B
  X 0.1666667 0.5000000
  Y 0.1666667 0.1666667

Another way: 其他方式:

table(df)/nrow(df)
#    V2
# V1          A         B
#   X 0.1666667 0.5000000
#   Y 0.1666667 0.1666667

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM