I don't know why, but not being able to generate the values for one id/week/category/dt
specifically, as you can see below, as well as not being able to generate for all data using my f2
function, it gives error in mutate
.. What am I doing wrong?
Code executable
library(dplyr)
df1<-structure(list(Id = c(1, 1, 1, 1, 1, 1), date = structure(c(19090,
19090, 19090, 19090, 19090, 19090), class = "Date"), date2 = structure(c(18962,18962, 18962, 18962, 18962, 18962), class = "Date"),
Week = c("Wednesday","Wednesday", "Wednesday", "Wednesday", "Wednesday",
"Wednesday"), DT = c(1, NA_character_, NA_character_,NA_character_, NA_character_, 1), Category = c("AB","CD", "EF", "GH", "IJ", "KL"),
Time = c(1.86, 4, 2.89, 0, 1, 2.4)), row.names = c(NA, -6L), class = c("tbl_df","tbl", "data.frame"))
> df1
# A tibble: 6 x 7
Id date date2 Week DT Category Time
<dbl> <date> <date> <chr> <chr> <chr> <dbl>
1 1 2022-04-08 2021-12-01 Wednesday 1 AB 1.86
2 1 2022-04-08 2021-12-01 Wednesday NA CD 4
3 1 2022-04-08 2021-12-01 Wednesday NA EF 2.89
4 1 2022-04-08 2021-12-01 Wednesday NA GH 0
5 1 2022-04-08 2021-12-01 Wednesday NA IJ 1
6 1 2022-04-08 2021-12-01 Wednesday 1 KL 2.4
f2 <- function(df1,idd,ds,codagr,dt) {
nms <- c('Time|time')
mtime <- df1 %>%
group_by(Id,Week = tools::toTitleCase(Week), Category,DT) %>%
summarise(across(matches(nms), mean, .names = 'Time',na.rm = TRUE), .groups = 'drop')
mtime <- transform(mtime, Time = format(round(Time, digits = 2), nsmall = 2))
mtime <- mtime %>%
filter(Id==idd,Week == ds, Category == codagr,DT==dt)
return(mtime)
}
Generate to specific id/week/category/dt
f2(df1,"1","Wednesday","AB","1")
Id Week Category DT Time
1 1 Wednesday AB 1 1.86
f2(df1,"1","Wednesday","IJ",NA)
[1] Id Week Category DT Time
<0 linhas> (ou row.names de comprimento 0)
Generate to all
Result <- df1 %>%
rowwise()
mutate(f2(df1,Id,Week,Category, DT))%>%
data.frame()
Error: Problem with `filter()` input `..1`.
i Input `..1` is `Id == idd`.
x object 'Id' not found
Result
correct output:
Id Week Category DT Time
1 1 Wednesday AB 1 1.86
2 1 Wednesday CD <NA> 4.00
3 1 Wednesday EF <NA> 2.89
4 1 Wednesday GH <NA> 0.00
5 1 Wednesday IJ <NA> 1.00
6 1 Wednesday KL 1 2.40