R中的频率计数 [英] Frequency counts in R
本文介绍了R中的频率计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这似乎是一个非常基本的R问题,但我希望得到一个答案.我有一个数据框,其格式为:
This may seem like a very basic R question, but I'd appreciate an answer. I have a data frame in the form of:
col1 col2
a g
a h
a g
b i
b g
b h
c i
我想将其转换为计数,因此结果将是这样.我试过使用table()函数,但似乎只能获取一列的计数.
I want to transform it into counts, so the outcome would be like this. I've tried using table () function, but seem to only be able to get the count for one column.
a b c
g 2 1 0
h 1 1 0
i 0 1 1
我如何在R中做到这一点?
How do I do it in R?
推荐答案
我不太确定您使用的是什么,但是table
对我来说很好!
I'm not really sure what you used, but table
works fine for me!
这是一个最小的可重现示例:
Here's a minimal reproducible example:
df <- structure(list(V1 = c("a", "a", "a", "b", "b", "b", "c"),
V2 = c("g", "h", "g", "i", "g", "h", "i")),
.Names = c("V1", "V2"), class = "data.frame",
row.names = c(NA, -7L))
table(df)
# V2
# V1 g h i
# a 2 1 0
# b 1 1 1
# 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
,而不是您想要的相同输出格式).
- Try
table(df[c(2, 1)])
(ortable(df$V2, df$V1)
) to swap the rows and columns. - Use
as.data.frame.matrix(table(df))
to get adata.frame
as your output. (as.data.frame
will create a longdata.frame
, not one in the same output format you desire).
这篇关于R中的频率计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文