I'd like to know why I'm getting my output with duplicate values. Notice that I have twice values for Wednesday
, Thursday
and Friday
. How can I fix this?
Executable code below:
library(dplyr)
library(tidyverse)
df1<-structure(list(Id = c(1, 1, 1, 1, 1, 1), date1 = c("2021-06-28",
"2021-06-28", "2021-06-28", "2021-06-28", "2021-06-28", "2021-06-28"),
date2 = c("2021-06-18","2021-06-19", "2021-06-20", "2021-06-25", "2021-06-26", "2021-06-27"),
Week = c("Wednesday","Thursday", "Friday", "Wednesday","Thursday", "Friday"),
DT = c(1, NA_character_, NA_character_,1, NA_character_, NA_character_), Category = c("AB","CD", "EF", "AB", "CD", "EF"),
Time = c(2, 4, 2, 4, 3, 4)), row.names = c(NA, -6L), class = c("tbl_df","tbl", "data.frame"))
f2 <- function(df1,idd,ds,codagr,dt) {
nms <- c('Time|time')
mtime <- df1 %>% mutate(DT = replace_na(DT, "")) %>%
filter(Id==idd,Week == ds, Category == codagr,DT == dt) %>%
group_by(Id,Week,Category,DT) %>%
summarise(across(matches(nms), mean, .names = 'Time',na.rm = TRUE), .groups = 'keep') %>%
mutate(Time = format(round(Time, digits = 2), nsmall = 2))
return(mtime)
}
df1 %>% mutate(DT = replace_na(DT, "")) %>%
rowwise %>%
mutate(f2(df1,Id,Week,Category, DT))%>%
select(-c(date1, date2))%>