Replacing missing quarter and missing data per quarter - r

Background
I've a quarterly data set where certain quarters and corresponding values are missing. The characteristics of the data set are:
Each group should have the same number of quarters but in practe quarters are missing
For missing quarter values are unknown
This is to be resolved by sourcing imputing next available value; for instance, as available via na.locf function
Example data
# Packages
Vectorize(require)(package = c("tidyverse", "zoo", "magrittr"),
character.only = TRUE)
# Seed
set.seed(123)
# Dummy data
dta <- data.frame(group = rep(LETTERS[1:5], 10)) %>%
group_by(group) %>%
mutate(qrtr = seq(
from = as.Date("01/01/2012", "%d/%m/%Y"),
to = as.Date("31/5/2014", "%d/%m/%Y"),
by = "quarter"
)) %>%
ungroup() %>%
mutate(qrtr = as.yearqtr(qrtr)) %>%
arrange(group, qrtr) %>%
mutate(value = sample(1:10, 50, replace = TRUE))
# Remove random rows
dta[sample(1:dim(dta)[1], 10), c(2, 3)] <- NA
dta %<>% na.omit()
Preview
# A tibble: 40 x 3
group qrtr value
<chr> <S3: yearqtr> <int>
1 A 2012 Q1 3
2 A 2012 Q2 8
3 A 2012 Q4 9
4 A 2013 Q1 10
5 A 2013 Q3 6
6 A 2013 Q4 9
7 A 2014 Q1 6
8 B 2012 Q1 10
9 B 2012 Q2 5
10 B 2012 Q3 7
# ... with 30 more rows
Problem
Create add rows within each group where quarter are missing. Total number of quarter is derived from sequence min(qrtr) to max(qrtr), in the context of existing code:
seq(from = as.Date("01/01/2012", "%d/%m/%Y"),
to = as.Date("31/5/2014", "%d/%m/%Y"),
by = "quarter")
First non-missing value should be carried forward for the missing value.
Desired results:
>> dta
# A tibble: 50 x 3
group qrtr value
<chr> <S3: yearqtr> <int>
1 A 2012 Q1 3
2 A 2012 Q2 8
3 A 2012 Q3 8
4 A 2012 Q4 9
5 A 2013 Q1 10
6 A 2013 Q2 10
7 A 2013 Q3 6
8 A 2013 Q4 9
9 A 2014 Q1 6
10 A 2015 Q1 6
# ... with 40 more rows
Proposed approaches
One approach would rely on making use of the expand, in order to convert implicitly missing values to explicitly missing values. This so far creates missing quarters but there is no clear way of creating missing observations for value column for where given quarter is missing.
dta %>%
# Append mixing quarters
expand(group, qrtr) %>%
left_join(data.frame(qrtr = as.yearqtr(
seq(
from = as.Date("01/01/2012", "%d/%m/%Y"),
to = as.Date("31/5/2014", "%d/%m/%Y"),
by = "quarter"
)
)), by = "qrtr") %>%
# TODO
# mutate(value = na.locf(value)) %>%
arrange(group, qrtr) -> dta_fixed

You seems to be interested in padr
library(padr)
library(zoo)
#convert to POSIXct as pad() expect it to be like this
dta$qrtr <- as.POSIXct(dta$qrtr,format="%Y %q")
dta %>%
pad(group="group") %>%
arrange(group, qrtr) %>%
mutate(qrtr = as.yearqtr(qrtr)) %>%
na.locf()
output is:
# A tibble: 49 x 3
group qrtr value
<chr> <chr> <chr>
1 A 2012 Q1 3
2 A 2012 Q2 8
3 A 2012 Q3 8
4 A 2012 Q4 9
5 A 2013 Q1 10
6 A 2013 Q2 10
7 A 2013 Q3 6
8 A 2013 Q4 9
9 A 2014 Q1 6
10 B 2012 Q1 10
# ... with 39 more rows

Use read.zoo to create a multivariate time series z with one column per group; merge that with a zero width series of quarters, run na.locf and then convert that back to long form.
We can omit:
the line with the merge if there is no quarter missing from every group -- in the example data in the question this is the case. i.e. for the data in the question we could omit the merge (although if we left it in it would not cause a problem)
the last line (the one with fortify.zoo) if we can work with the 10 x 5 multivariate time series z directly, which may actually be more convenient, e.g. library(ggplot); autoplot(z, facet = NULL) + scale_x_yearqtr() or the same without the facet argument will plot it using ggplot2 graphics using 1 or 5 panels.
This does not use any packages that the question is not already using anyways and works directly with the index in the original "yearqtr" class without conversion.
library(zoo)
z <- read.zoo(dat, index = "qrtr", split = "group")
z <- merge(z, zoo(, seq(start(z), end(z), 1/4))
z <- na.locf(z)
fortify.zoo(z, melt = TRUE)
This could alternately be expressed as the following pipeline:
library(dplyr) # or library(magrittr)
library(zoo)
dta %>%
read.zoo(index = "qrtr", split = "group") %>%
merge(zoo(, start(z), end(z), 1/4)) %>%
na.locf %>%
fortify.zoo(melt = TRUE)
Updates Have added pipeline and made a number of wording improvements and clarifications.

Related

How to calculate rolling mean for multiple columns at once with a groupby and select in dplyr, while ignoring the groupby columns

I am trying to get rolling means for many columns at once, but I am running into difficulty because my grouping variables are not numeric.
If I were to do a rolling mean for one column at a time, my code should look something like this :
NHLReg2<-arrange(NHLReg2,season,team,gameId) %>% group_by(season,team)%>% mutate(xGF= rollapply(xGoalsFor, list( seq(21)), sum, partial = TRUE, fill = NA))
I have attempted to use dplyr in order to do many columns at the same time:
NHLPP3<-arrange(NHLPP2,season,team,gameId) %>%
group_by(season,team)%>%
select(c(1,2,11:112)) %>%
lapply(function(x){ if(class(x) == "numeric"){
rollapply(x, width=list(-seq(21)), FUN=function(x){sum(x,
na.rm=T)},partial = T, fill = NA)
}else{
return(x)
}
})%>% as.data.frame()
This does solve the problem of ignoring the character/grouping variables for the rollapply, but it causes the groupby statement to have no effect. I have left some sample data below, pretend v1 and v2 are the grouping variables and v3 and v4 are the columns of interest to calculate a rolling mean.
v1<-c('a','a','a','a','a','a','a','a','b','b','b','b','b','b','b')
v2<-c('2010','2010','2010','2010','2010','2010','2010','2010','2020','2020','2020','2020','2020','2020','2020')
v3<-c(1,2,3,4,1,4,5,6,13,5,6,13,4,65,8)
v4<-c(6,13,5,6,13,4,65,8,1,2,3,4,1,4,5)
Data<-as.data.frame(t(rbind(v1,v2,v3,v4)))
Thank you.
Data, as defined in the question, has no numeric columns. It is all factors. We fix the definition below. Then we use mutate_at to just apply rollapplyr to the non-grouping columns. So that we can use Data, we roll the sum over the prior 3 values rather than the prior 21. An alternative to the mutate_at line would be mutate_if(is.numeric, ~ rollapplyr(...same...)) .
library(dplyr)
library(zoo)
Data <- data.frame(v1, v2, v3, v4) # v1, v2, v3, v4 are from question
Data %>%
group_by(v1, v2) %>%
mutate_at(vars(-group_cols()),
~ rollapplyr(.x, list(-seq(3)), sum, na.rm = FALSE, partial = TRUE, fill = NA)) %>%
ungroup
giving:
# A tibble: 15 x 4
v1 v2 v3 v4
<fct> <fct> <dbl> <dbl>
1 a 2010 NA NA
2 a 2010 1 6
3 a 2010 3 19
4 a 2010 6 24
5 a 2010 9 24
6 a 2010 8 24
7 a 2010 9 23
8 a 2010 10 82
9 b 2020 NA NA
10 b 2020 13 1
11 b 2020 18 3
12 b 2020 24 6
13 b 2020 24 9
14 b 2020 23 8
15 b 2020 82 9

Deleting duplicated rows based on condition (position)

I have a dataset that looks something like this
df <- data.frame("id" = c("Alpha", "Alpha", "Alpha","Alpha","Beta","Beta","Beta","Beta"),
"Year" = c(1970,1970,1970,1971,1980,1980,1981,1982),
"Val" = c(2,3,-2,5,2,5,3,5))
I have mulple observations for each id and time identifier - e.g. I have 3 different alpha 1970 values. I would like to retain only one observation per id/year most notably the last one that appears in for each id/year.
the final dataset should look something like this:
final <- data.frame("id" = c("Alpha","Alpha","Beta","Beta","Beta"),
"Year" = c(1970,1971,1980,1981,1982),
"Val" = c(-2,5,5,3,5))
Does anyone know how I can approach the problem?
Thanks a lot in advance for your help
If you are open to a data.table solution, this can be done quite concisely:
library(data.table)
setDT(df)[, .SD[.N], by = c("id", "Year")]
#> id Year Val
#> 1: Alpha 1970 -2
#> 2: Alpha 1971 5
#> 3: Beta 1980 5
#> 4: Beta 1981 3
#> 5: Beta 1982 5
by = c("id", "Year") groups the data.table by id and Year, and .SD[.N] then returns the last row within each such group.
How about this?
library(tidyverse)
df <- data.frame("id" = c("Alpha", "Alpha", "Alpha","Alpha","Beta","Beta","Beta","Beta"),
"Year" = c(1970,1970,1970,1971,1980,1980,1981,1982),
"Val" = c(2,3,-2,5,2,5,3,5))
final <-
df %>%
group_by(id, Year) %>%
slice(n()) %>%
ungroup()
final
#> # A tibble: 5 x 3
#> id Year Val
#> <fct> <dbl> <dbl>
#> 1 Alpha 1970 -2
#> 2 Alpha 1971 5
#> 3 Beta 1980 5
#> 4 Beta 1981 3
#> 5 Beta 1982 5
Created on 2019-09-29 by the reprex package (v0.3.0)
Translates to "within each id-Year group, take only the row where the row number is equal to the size of the group, i.e. it's the last row under the current ordering."
You could also use either filter(), e.g. filter(row_number() == n()), or distinct() (and then you wouldn't even have to group), e.g. distinct(id, Year, .keep_all = TRUE) - but distinct functions take the first distinct row, so you'd need to reverse the row ordering here first.
An option with base R
aggregate(Val ~ ., df, tail, 1)
# id Year Val
#1 Alpha 1970 -2
#2 Alpha 1971 5
#3 Beta 1980 5
#4 Beta 1981 3
#5 Beta 1982 5
If we need to select the first row
aggregate(Val ~ ., df, head, 1)

R: Grouping in a hierarchy

I'm working on a dataset with a with grouping-system with six digits. The first two digits denote grouping on the top-level, the next two denote different sub-groups, and the last two digits denote specific type within the sub-group. I want to group the data to the top level in the hierarchy (two first digits only), and count unique names in each group.
An example for the GroupID 010203:
01 denotes BMW
02 denotes 3-series
03 denotes 320i (the exact model)
All I care about in this example is how many of each brand there is.
Toy dataset and wanted output:
df <- data.table(Quarter = c('Q4', 'Q4', 'Q4', 'Q4', 'Q3'),
GroupID = c(010203, 150503, 010101, 150609, 010000),
Name = c('AAAA', 'AAAA', 'BBBB', 'BBBB', 'CCCC'))
Output:
Quarter Group Counts
Q3 01 1
Q4 01 2
Q4 15 2
Using data.table we could do:
library(data.table)
dt[, Group := substr(GroupID, 1, 2)][
, Counts := .N, by = list(Group, Quarter)][
, head(.SD, 1), by = .(Quarter, Group, Counts)][
, .(Quarter, Group, Counts)]
Returns:
Quarter Group Counts
1: Q4 01 2
2: Q4 15 2
3: Q3 01 1
With dplyr and stringr we could do something like:
library(dplyr)
library(stringr)
df %>%
mutate(Group = str_sub(GroupID, 1, 2)) %>%
group_by(Group, Quarter) %>%
summarise(Counts = n()) %>%
ungroup()
Returns:
# A tibble: 3 x 3
Group Quarter Counts
<chr> <fct> <int>
1 01 Q3 1
2 01 Q4 2
3 15 Q4 2
Since you are already using data.table, you can do:
df[, Group := substr(GroupID,1,2)]
df <- df[,Counts := .N, .(Group,Quarter)][,.(Group, Quarter, Counts)]
df <- unique(df)
print(df)
Group Quarter Counts
1: 10 Q4 2
2: 15 Q4 2
3: 10 Q3 1
Here's my simple solution with plyr and base R, it is lightening fast.
library(plyr)
df$breakid <- as.character((substr(df$GroupID, start =0 , stop = 2)))
d <- plyr::count(df, c("Quarter", "breakid"))
Result
Quarter breakid freq
Q3 01 1
Q4 01 2
Q4 15 2
Alternatively, using tapply (and data.table indexing):
df$Brand <- substr(df$GroupID, 1, 2)
tapply(df$Brand, df[, .(Quarter, Brand)], length)
(If you don't care about the output being a matrix).

R: Consolidating duplicate observations?

I have a large data frame with approximately 500,000 observations (identified by "ID") and 150+ variables. Some observations only appear once; others appear multiple times (upwards of 10 or so). I would like to "collapse" these multiple observations so that there is only one row per unique ID, and that all information in columns 2:150 are concatenated. I do not need any calculations run on these observations, just a quick munging.
I've tried:
df.new <- group_by(df,"ID")
and also:
library(data.table)
dt = data.table(df)
dt.new <- dt[, lapply(.SD, na.omit), by = "ID"]
and unfortunately neither have worked. Any help is appreciated!
Using basic R:
df = data.frame(ID = c("a","a","b","b","b","c","d","d"),
day = c("1","2","3","4","5","6","7","8"),
year = c(2016,2017,2017,2016,2017,2016,2017,2016),
stringsAsFactors = F)
> df
ID day year
1 a 1 2016
2 a 2 2017
3 b 3 2017
4 b 4 2016
5 b 5 2017
6 c 6 2016
7 d 7 2017
8 d 8 2016
Do:
z = aggregate(df[,2:3],
by = list(id = df$ID),
function(x){ paste0(x, collapse = "/") }
)
Result:
> z
id day year
1 a 1/2 2016/2017
2 b 3/4/5 2017/2016/2017
3 c 6 2016
4 d 7/8 2017/2016
EDIT
If you want to avoid "collapsing" NA do:
z = aggregate(df[,2:3],
by = list(id = df$ID),
function(x){ paste0(x[!is.na(x)],collapse = "/") })
For a data frame like:
> df
ID day year
1 a 1 2016
2 a 2 NA
3 b 3 2017
4 b 4 2016
5 b <NA> 2017
6 c 6 2016
7 d 7 2017
8 d 8 2016
The result is:
> z
id day year
1 a 1/2 2016
2 b 3/4 2017/2016/2017
3 c 6 2016
4 d 7/8 2017/2016
I have had a similar problem in the past, but I wasn't dealing with several copies of the same data. It was in many cases just 2 instances and in some cases 3 instances. Below was my approach. Hopefully, it will help.
idx <- duplicated(df$key) | duplicated(df$key, fromLast=TRUE) # get the index of the duplicate entries. Or will help get the original value too.
dupes <- df[idx,] # get duplicated values
non_dupes <- df[!idx,] # get all non duplicated values
temp <- dupes %>% group_by(key) %>% # roll up the duplicated ones.
fill_(colnames(dupes), .direction = "down") %>%
fill_(colnames(dupes), .direction = "up") %>%
slice(1)
Then it is easy to merge back the temp and the non_dupes.
EDIT
I would highly recommend to filter the df to the only the population as much as possible and relevant for your end goal as this process could take some time.
What about?
df %>%
group_by(ID) %>%
summarise_each(funs(paste0(., collapse = "/")))
Or reproducible...
iris %>%
group_by(Species) %>%
summarise_each(funs(paste0(., collapse = "/")))

R- data frame, separating by value of col [duplicate]

I have a dataframe and I would like to count the number of rows within each group. I reguarly use the aggregate function to sum data as follows:
df2 <- aggregate(x ~ Year + Month, data = df1, sum)
Now, I would like to count observations but can't seem to find the proper argument for FUN. Intuitively, I thought it would be as follows:
df2 <- aggregate(x ~ Year + Month, data = df1, count)
But, no such luck.
Any ideas?
Some toy data:
set.seed(2)
df1 <- data.frame(x = 1:20,
Year = sample(2012:2014, 20, replace = TRUE),
Month = sample(month.abb[1:3], 20, replace = TRUE))
Current best practice (tidyverse) is:
require(dplyr)
df1 %>% count(Year, Month)
Following #Joshua's suggestion, here's one way you might count the number of observations in your df dataframe where Year = 2007 and Month = Nov (assuming they are columns):
nrow(df[,df$YEAR == 2007 & df$Month == "Nov"])
and with aggregate, following #GregSnow:
aggregate(x ~ Year + Month, data = df, FUN = length)
dplyr package does this with count/tally commands, or the n() function:
First, some data:
df <- data.frame(x = rep(1:6, rep(c(1, 2, 3), 2)), year = 1993:2004, month = c(1, 1:11))
Now the count:
library(dplyr)
count(df, year, month)
#piping
df %>% count(year, month)
We can also use a slightly longer version with piping and the n() function:
df %>%
group_by(year, month) %>%
summarise(number = n())
or the tally function:
df %>%
group_by(year, month) %>%
tally()
An old question without a data.table solution. So here goes...
Using .N
library(data.table)
DT <- data.table(df)
DT[, .N, by = list(year, month)]
The simple option to use with aggregate is the length function which will give you the length of the vector in the subset. Sometimes a little more robust is to use function(x) sum( !is.na(x) ).
Create a new variable Count with a value of 1 for each row:
df1["Count"] <-1
Then aggregate dataframe, summing by the Count column:
df2 <- aggregate(df1[c("Count")], by=list(Year=df1$Year, Month=df1$Month), FUN=sum, na.rm=TRUE)
An alternative to the aggregate() function in this case would be table() with as.data.frame(), which would also indicate which combinations of Year and Month are associated with zero occurrences
df<-data.frame(x=rep(1:6,rep(c(1,2,3),2)),year=1993:2004,month=c(1,1:11))
myAns<-as.data.frame(table(df[,c("year","month")]))
And without the zero-occurring combinations
myAns[which(myAns$Freq>0),]
If you want to include 0 counts for month-years that are missing in the data, you can use a little table magic.
data.frame(with(df1, table(Year, Month)))
For example, the toy data.frame in the question, df1, contains no observations of January 2014.
df1
x Year Month
1 1 2012 Feb
2 2 2014 Feb
3 3 2013 Mar
4 4 2012 Jan
5 5 2014 Feb
6 6 2014 Feb
7 7 2012 Jan
8 8 2014 Feb
9 9 2013 Mar
10 10 2013 Jan
11 11 2013 Jan
12 12 2012 Jan
13 13 2014 Mar
14 14 2012 Mar
15 15 2013 Feb
16 16 2014 Feb
17 17 2014 Mar
18 18 2012 Jan
19 19 2013 Mar
20 20 2012 Jan
The base R aggregate function does not return an observation for January 2014.
aggregate(x ~ Year + Month, data = df1, FUN = length)
Year Month x
1 2012 Feb 1
2 2013 Feb 1
3 2014 Feb 5
4 2012 Jan 5
5 2013 Jan 2
6 2012 Mar 1
7 2013 Mar 3
8 2014 Mar 2
If you would like an observation of this month-year with 0 as the count, then the above code will return a data.frame with counts for all month-year combinations:
data.frame(with(df1, table(Year, Month)))
Year Month Freq
1 2012 Feb 1
2 2013 Feb 1
3 2014 Feb 5
4 2012 Jan 5
5 2013 Jan 2
6 2014 Jan 0
7 2012 Mar 1
8 2013 Mar 3
9 2014 Mar 2
For my aggregations I usually end up wanting to see mean and "how big is this group" (a.k.a. length).
So this is my handy snippet for those occasions;
agg.mean <- aggregate(columnToMean ~ columnToAggregateOn1*columnToAggregateOn2, yourDataFrame, FUN="mean")
agg.count <- aggregate(columnToMean ~ columnToAggregateOn1*columnToAggregateOn2, yourDataFrame, FUN="length")
aggcount <- agg.count$columnToMean
agg <- cbind(aggcount, agg.mean)
A sql solution using sqldf package:
library(sqldf)
sqldf("SELECT Year, Month, COUNT(*) as Freq
FROM df1
GROUP BY Year, Month")
Using collapse package in R
library(collapse)
library(magrittr)
df %>%
fgroup_by(year, month) %>%
fsummarise(number = fNobs(x))
library(tidyverse)
df_1 %>%
group_by(Year, Month) %>%
summarise(count= n())
Considering #Ben answer, R would throw an error if df1 does not contain x column. But it can be solved elegantly with paste:
aggregate(paste(Year, Month) ~ Year + Month, data = df1, FUN = NROW)
Similarly, it can be generalized if more than two variables are used in grouping:
aggregate(paste(Year, Month, Day) ~ Year + Month + Day, data = df1, FUN = NROW)
You can use by functions as by(df1$Year, df1$Month, count) that will produce a list of needed aggregation.
The output will look like,
df1$Month: Feb
x freq
1 2012 1
2 2013 1
3 2014 5
---------------------------------------------------------------
df1$Month: Jan
x freq
1 2012 5
2 2013 2
---------------------------------------------------------------
df1$Month: Mar
x freq
1 2012 1
2 2013 3
3 2014 2
>
There are plenty of wonderful answers here already, but I wanted to throw in 1 more option for those wanting to add a new column to the original dataset that contains the number of times that row is repeated.
df1$counts <- sapply(X = paste(df1$Year, df1$Month),
FUN = function(x) { sum(paste(df1$Year, df1$Month) == x) })
The same could be accomplished by combining any of the above answers with the merge() function.
If your trying the aggregate solutions above and you get the error:
invalid type (list) for variable
Because you're using date or datetime stamps, try using as.character on the variables:
aggregate(x ~ as.character(Year) + Month, data = df, FUN = length)
On one or both of the variables.
I usually use table function
df <- data.frame(a=rep(1:8,rep(c(1,2,3, 4),2)),year=2011:2021,month=c(1,3:10))
new_data <- as.data.frame(table(df[,c("year","month")]))

Resources