Hi All,
Looking to apply for loop correctly on grouped data. Achieving correct result per group without applying for loop
Thanks for your help in advance!
library(tidyverse)
# Example data
df <- data.frame(
stringsAsFactors = FALSE,
check.names = FALSE,
ACCTDT = c(202309L,202309L,
202309L,202309L,202310L,202310L,202310L,202310L,
202309L,202309L,202309L,202310L,202310L,
202310L),
`ACT/FC` = c("ACT","ACT","ACT",
"ACT","FC","FC","FC","FC","ACT","ACT",
"ACT","FC","FC","FC"),
Country = c("CA","CA","CA",
"CA","CA","CA","CA","CA","CA","CA","CA","CA",
"CA","CA"),
Type = c("A","A","A","A",
"A","A","A","A","B","B","B","B","B","B"),
Code = c("A_1","A_2","A_3",
"A_4","A_1","A_2","A_3","A_4","A_1","A_2",
"A_3","A_1","A_2","A_3"),
Sales = c(100L,90L,80L,
120L,110L,NA,NA,NA,89L,130L,96L,125L,NA,NA)
)
# Works fine without For Loop as below
df2 <- df
df2 <- df2%>%
group_by(ACCTDT, `ACT/FC`, Country, Type, Code) %>%
mutate(Sales = Sales,
`New_Sale`= if_else(`ACT/FC` == "ACT", NA, Sales)
)
# For Grouped Data using For Loop
df1 <- df
# New Sales
df$"New_Sale" <- integer(length(df$Sales))
df1$"New_Sale" <- integer(length(df$Sales))
# Doesn't work for all groups
# Works only for first group
for(i in seq_along(df)){
if(df$`ACT/FC`[i] == "ACT"){
df$`New_Sale`[i] = NA
} else{
df$`New_Sale`[i] = df$Sales[i]
}
}
# Trying for all groups
# No result here
for(i in seq_along(df1)){
df1%>%
group_by(ACCTDT, `ACT/FC`, Country, Type, Code) %>%
mutate(Sales = Sales, `New_Sale`= ifelse(
`ACT/FC`[i] == "ACT", NA, Sales[i]
)
)
}