Question

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.*

Was it helpful?

Solution

Use the table function to create tables of counts:

> 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(table(df))
   V2
V1          A         B
  X 0.1666667 0.5000000
  Y 0.1666667 0.1666667

OTHER TIPS

Another way:

table(df)/nrow(df)
#    V2
# V1          A         B
#   X 0.1666667 0.5000000
#   Y 0.1666667 0.1666667
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top