R生成频率表

mic*_*jas 0 r vector frequency

我有这样的样本矢量:

v <- c(1, 2, 1, 3, 2, 3, 3, 4, 1, 4)
Run Code Online (Sandbox Code Playgroud)

我想得到的是频率表,它会告诉我数字的频率,然后是另一个数字.

输出:

  1 2 3 4
1 0 1 0 1
2 1 0 1 0
3 1 1 1 0
4 1 0 1 0
Run Code Online (Sandbox Code Playgroud)

然后以百分比表示相同的值.

Jos*_*ien 5

这是一种方式:

## Construct a data frame in which each row is a pair of consecutive characters.
df <- data.frame(a=head(v,-1), b=v[-1])
## tabulate frequencies of the ordered pairs
res <- xtabs(~a+b, df)
res
#    b
# a   1 2 3 4
#   1 0 1 1 1
#   2 1 0 1 0
#   3 0 1 1 1
#   4 1 0 0 0

res/sum(res)
#    b
# a           1         2         3         4
#   1 0.0000000 0.1111111 0.1111111 0.1111111
#   2 0.1111111 0.0000000 0.1111111 0.0000000
#   3 0.0000000 0.1111111 0.1111111 0.1111111
#   4 0.1111111 0.0000000 0.0000000 0.0000000
Run Code Online (Sandbox Code Playgroud)