R中的频率计数

R中的频率计数

这似乎是一个非常基本的R问题,但我很感激答案。我有一个以下形式的数据框:


col1    col2

a   g

a   h

a   g

b   i

b   g

b   h

c   i

我想将它转化为计数,所以结果将是这样的。我尝试过使用table()函数,但似乎只能获得一列的计数。


    a   b   c

g   2   1   0

h   1   1   0

i   0   1   1

我怎么在R?


千巷猫影
浏览 1773回答 2
2回答

眼眸繁星

我不太确定你用过什么,但table对我来说效果很好!这是一个可重复性最小的例子:df <- structure(list(V1 = c("a", "a", "a", "b", "b", "b", "c"),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;V2 = c("g", "h", "g", "i", "g", "h", "i")),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Names = c("V1", "V2"), class = "data.frame",&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; row.names = c(NA, -7L))table(df)#&nbsp; &nbsp; V2# V1&nbsp; g h i#&nbsp; &nbsp;a 2 1 0#&nbsp; &nbsp;b 1 1 1#&nbsp; &nbsp;c 0 0 1笔记:尝试table(df[c(2, 1)])(或table(df$V2, df$V1))交换行和列。使用as.data.frame.matrix(table(df))得到一个data.frame作为输出。(as.data.frame将创建一个长的data.frame,而不是一个你想要的相同输出格式)。

一只萌萌小番薯

使用f@Ananda你可以使用dcastlibrary(reshape2)> dcast(f, V1~V2)Using V2 as value column: use value.var to override.Aggregation function missing: defaulting to length&nbsp; V1&nbsp; g&nbsp; h&nbsp; i1 a&nbsp; &nbsp;2&nbsp; 1&nbsp; 02 b&nbsp; &nbsp;1&nbsp; 1&nbsp; 13 c&nbsp; &nbsp;0&nbsp; 0&nbsp; 1但是,我写这篇文章只是为了以后你可能需要的不仅仅是table(在这种情况下,这是最简单的正确答案),例如:set.seed(1)f$var <- rnorm(7)> f&nbsp; V1 V2&nbsp; &nbsp; &nbsp; &nbsp; var1 a&nbsp; &nbsp;g -0.62645382 a&nbsp; &nbsp;h&nbsp; 0.18364333 a&nbsp; &nbsp;g -0.83562864 b&nbsp; &nbsp;i&nbsp; 1.59528085 b&nbsp; &nbsp;g&nbsp; 0.32950786 b&nbsp; &nbsp;h -0.82046847 c&nbsp; &nbsp;i&nbsp; 0.4874291> dcast(f, V1~V2, value.var="var", fun.aggregate=sum)&nbsp; V1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; g&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; h&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;i1 a&nbsp; -1.4620824&nbsp; 0.1836433 0.00000002 b&nbsp; &nbsp;0.3295078 -0.8204684 1.59528083 c&nbsp; &nbsp;0.0000000&nbsp; 0.0000000 0.4874291
打开App,查看更多内容
随时随地看视频慕课网APP