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
. .
. .
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
I tried to do this:
n_row <- nrow(dat1_frame %.% group_by(MONTH-YEAR))
but it does not produce the desired output.How can I do that?
Here is another way of using
aggregate
to count rows by group:Using the example data set that Ananda dummied up, here's an example using
aggregate()
, which is part of core R.aggregate()
just needs something to count as function of the different values ofMONTH-YEAR
. In this case, I usedVALUE
as the thing to count:which gives you..
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:
Here's the calculation of the number of rows per group, in two output display formats:
Suppose we have a df_data data frame as below
To count number of rows in df_data grouped by MONTH-YEAR column, you can use:
summary function will create a table from the factor argument, then create a vector for the result (line 7 & 8)
This will give you the answer, if "MONTH-YEAR" is a variable. First, try unique(data$MONTH-YEAR) and see if it returns unique values (no duplicates).
Then above simple split-apply-combine will return what you are looking for.
Try using the count function in dplyr:
I am not sure how you got MONTH-YEAR as a variable name. My R version does not allow for such a variable name, so I replaced it with MONTH.YEAR.
As a side note, the mistake in your code was that
dat1_frame %.% group_by(MONTH-YEAR)
without asummarise
function returns the original data frame without any modifications. So, you want to use