计算R的data.frame中的成员资格的频率

时间:2013-08-22 09:23:23

标签: r dataframe

我有以下data.frame:

authors <- data.frame(
    surname = I(c("Tukey", "Venables", "Tierney", "Ripley", "McNeil")),
    nationality = c("US", "Australia", "US", "UK", "Australia"),
    deceased = c("yes", rep("no", 3),"noinfo"))
产生此输出的

      surname nationality deceased
1    Tukey          US      yes
2 Venables   Australia       no
3  Tierney          US       no
4   Ripley          UK       no
5   McNeil   Australia   noinfo

我想要做的是deceased的频率为nationality。 产生这个输出:

US yes 1
US no  1
US noinfo 0
Australia yes 0
Australia no 1
Australia noinfo 1
UK yes 0
UK no 1
UK noinfo 0

目前,我只能通过tables显示统计信息。

stat <- table(authors)

我不确定如何通过访问表格的元素来继续。 建议将不胜感激。

1 个答案:

答案 0 :(得分:3)

您需要table关于您想要发生的事情......

table( authors[ c("nationality" , "deceased" ) ] )
#           deceased
#nationality no noinfo yes
#  Australia  1      1   0
#  UK         1      0   0
#  US         1      0   1

要获得您想要的完全输出...将其转换为data.frame ....

data.frame( table( authors[ c("nationality" , "deceased" ) ] ) )
#  nationality deceased Freq
#1   Australia       no    1
#2          UK       no    1
#3          US       no    1
#4   Australia   noinfo    1
#5          UK   noinfo    0
#6          US   noinfo    0
#7   Australia      yes    0
#8          UK      yes    0
#9          US      yes    1