I'm struggling with a problem here and hope you guys can help.. I have some data in the following format (see picture):
structure(list(Activity = 1:4, Date1 = c("01/09/2019", "01/09/2019",
"01/09/2019", "01/09/2019"), Amount1 = c(10L, 20L, 30L, 40L),
Date2 = c("01/10/2019", "01/10/2019", "01/10/2019", NA),
Amount2 = c(32L, 34L, 12L, NA), Date3 = c("01/11/2019", "01/11/2019",
"01/11/2019", NA), Amount3 = c(54L, 12L, 43L, NA), Date4 = c("01/12/2019",
NA, "01/12/2019", NA), Amount4 = c(56L, NA, 124L, NA)), row.names = c(NA,
-4L), class = c("tbl_df", "tbl", "data.frame"), spec = structure(list(
cols = list(Activity = structure(list(), class = c("collector_integer",
"collector")), Date1 = structure(list(), class = c("collector_character",
"collector")), Amount1 = structure(list(), class = c("collector_integer",
"collector")), Date2 = structure(list(), class = c("collector_character",
"collector")), Amount2 = structure(list(), class = c("collector_integer",
"collector")), Date3 = structure(list(), class = c("collector_character",
"collector")), Amount3 = structure(list(), class = c("collector_integer",
"collector")), Date4 = structure(list(), class = c("collector_character",
"collector")), Amount4 = structure(list(), class = c("collector_integer",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector"))), class = "col_spec"))
There can be hundreds of activities and all of these can have 0, 1, 2, 3, or 4 entries in date and amounts. I need to somehow "transpose" this into this format:
My thinking is, that this can be solved with a nested while loop inside a for loop, but I'm not very fluent in R and therefore I'm feeling a bit lost.
A few things to note:
- There can be many activities (not limited to just the 4 in the example)
- The activities can have input in any of the four "set" of columns -> date and amount, but it can also have no input.
- The end result need not to be ordered, I just need the specific format so we can enter this into a forecast model in another programme.
Please let me know if you need any clarifications on the above - hope you are able to help me here! :)
/Jacob