I have the following data:
structure(list(Date = c("01.08.2018", "02.08.2018", "03.08.2018",
"04.08.2018", "31.08.2018", "06.04.2019", "07.04.2019", "08.04.2019",
"01.08.2018", "02.08.2018", "03.08.2018", "04.08.2018", "06.04.2019",
"07.04.2019", "08.04.2019", "01.08.2018", "02.08.2018", "03.08.2018",
"04.08.2018", "05.08.2018", "07.04.2019", "30.04.2019"), Name = c("A",
"A", "A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B",
"B", "C", "C", "C", "C", "C", "C", "C"), Rating = c(1L, 1L, 1L,
3L, 3L, 4L, 4L, 4L, 3L, 3L, 2L, 2L, 2L, 1L, 1L, 1L, 3L, 3L, 3L,
5L, 5L, 5L), Size = c(1234L, 24123L, 23L, 1L, 23L, 3L, 23L, 4L,
323L, 3424L, 523L, 234L, 35L, 354L, 45L, 23L, 46L, 456L, 546L,
24L, 134L, 1L), Company = c("hello", "hello", "hello", "", "",
"bonjour", "bonjour", "bonjour", "", "", "hallo", "hallo", "hallo",
"hallo", "", "", "hallo", "hallo", "hallo", "", "", "hallo")), class = "data.frame", row.names = c(NA,
-22L))
First, I would like to add the sum of the column Size for each Company. For that I have the following code:
Data <- Data %>%
group_by(Company, Date) %>%
dplyr:: mutate(Sum_Size = sum(Size))
Now with this code, R treats the NA values in the column Company as one group. However, I don't want this to be one group. If the column Company is NA, then I would like to have the value of the column Size to be in the Sum_Size Column.
For that I have the following code:
Test <- Data %>%
dplyr:: mutate(Sum_Size=replace(Sum_Size, is.na(Company), Size))
However, the problem now is that with the code above, e.g. in row 9 Sum_Size is still the same as before and not equal to the value in column Size. What do I need to adjust in the code to achieve my desired outcome?