![](/img/trans.png)
[英]How to generate a frequency table in R with with cumulative frequency and relative frequency
[英]R Generate frequency table
我有這樣的樣本矢量:
v <- c(1, 2, 1, 3, 2, 3, 3, 4, 1, 4)
我想得到的是頻率表,它將告訴我數字的頻率,然后是另一個數字。
輸出:
1 2 3 4
1 0 1 0 1
2 1 0 1 0
3 1 1 1 0
4 1 0 1 0
然后是相同的百分比值。
這是一種方法:
## 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
如果我認為您的意思是正確的,請嘗試:
xtabs(~v[-1]+v[1:(length(v)-1)])
v[1:(length(v) - 1)]
v[-1] 1 2 3 4
1 0 1 0 1
2 1 0 1 0
3 1 1 1 0
4 1 0 1 0
這與您的預期輸出不匹配,但是我不確定您是如何實現的。
要獲取百分比,請使用prop.table
:
prop.table(xtabs(~v[-1]+v[1:(length(v)-1)]))*100
v[1:(length(v) - 1)]
v[-1] 1 2 3 4
1 0.00000 11.11111 0.00000 11.11111
2 11.11111 0.00000 11.11111 0.00000
3 11.11111 11.11111 11.11111 0.00000
4 11.11111 0.00000 11.11111 0.00000
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.