基于组计算 R 中数据框中的行数 [英] count number of rows in a data frame in R based on group
问题描述
我在 R
中有一个像这样的数据框:
I have a data frame in R
like this:
ID MONTH-YEAR VALUE
110 JAN. 2012 1000
111 JAN. 2012 2000
. .
. .
121 FEB. 2012 3000
131 FEB. 2012 4000
. .
. .
因此,每年的每个月都有 n
行,它们可以按任何顺序排列(意味着它们都没有连续性并且处于中断状态).我想计算每个 MONTH-YEAR
有多少行,即 JAN 有多少行.2012 年,2 月有多少.2012 年等等.像这样:
So, for each month of each year there are n
rows and they can be in any order(mean they all are not in continuity and are at breaks). I want to calculate how many rows are there for each MONTH-YEAR
i.e. how many rows are there for JAN. 2012, how many for FEB. 2012 and so on. Something like this:
MONTH-YEAR NUMBER OF ROWS
JAN. 2012 10
FEB. 2012 13
MAR. 2012 6
APR. 2012 9
我尝试这样做:
n_row <- nrow(dat1_frame %.% group_by(MONTH-YEAR))
但它没有产生所需的输出.我该怎么做?
but it does not produce the desired output.How can I do that?
推荐答案
下面的示例展示了 table(.)
(或者,更紧密地匹配您想要的输出,data.frame(table(.))
符合您的要求.
Here's an example that shows how table(.)
(or, more closely matching your desired output, data.frame(table(.))
does what it sounds like you are asking for.
另请注意如何以其他人可以复制和粘贴到他们的会话中的方式共享可重现的样本数据.
Note also how to share reproducible sample data in a way that others can copy and paste into their session.
这是(可重现的)示例数据:
Here's the (reproducible) sample data:
mydf <- structure(list(ID = c(110L, 111L, 121L, 131L, 141L),
MONTH.YEAR = c("JAN. 2012", "JAN. 2012",
"FEB. 2012", "FEB. 2012",
"MAR. 2012"),
VALUE = c(1000L, 2000L, 3000L, 4000L, 5000L)),
.Names = c("ID", "MONTH.YEAR", "VALUE"),
class = "data.frame", row.names = c(NA, -5L))
mydf
# ID MONTH.YEAR VALUE
# 1 110 JAN. 2012 1000
# 2 111 JAN. 2012 2000
# 3 121 FEB. 2012 3000
# 4 131 FEB. 2012 4000
# 5 141 MAR. 2012 5000
这里是每组行数的计算,两种输出显示格式:
Here's the calculation of the number of rows per group, in two output display formats:
table(mydf$MONTH.YEAR)
#
# FEB. 2012 JAN. 2012 MAR. 2012
# 2 2 1
data.frame(table(mydf$MONTH.YEAR))
# Var1 Freq
# 1 FEB. 2012 2
# 2 JAN. 2012 2
# 3 MAR. 2012 1
这篇关于基于组计算 R 中数据框中的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!