mardi 15 juin 2021

Replace negative values in a row based on conditions with grouping and conditions in R

I have a dataframe like this,

Industry = c("Industry1", "Industry1", "Industry1", "Industry2", "Industry2", "Industry3")
calc = c(-1.2345, 67890, 45678, -9.86544, 32456, 56789)
cy = c(0, 2019, 2017, 2016, 0, 2015, 2018)
py = c(0, 2018, 2016, 2015, 0, 2014, 2017)

data = data.frame(Industry, calc, cy, py, stringsAsFactors = FALSE)

I want to replace the negative values in calc column when cy = 0 and py = 0 by calculating the mean of calc column with grouping according to the industry. I have tried the following,

data = data %>% 
  group_by("Industry") %>% 
  mutate(calc = ifelse(cy == 0 & py == 0, summarise(calc = mean(calc)), calc))

But this isn't working. Can anyone help me with this?

Aucun commentaire:

Enregistrer un commentaire