Not sure how to word this issue concisely, so may be a bad title and the answer may be out there already. I'm essentially having an issue with a nested for loop to insert values into a new dataframe.
I have a large datafile with repeated names and associated investments and bonuses that need rearranging to create a new Table/dataframe with totals for each of the associated columns. Here is a simple for of the data table that I have:
I have written the following code with the Test Data a csv file written in Excel and saved as Book1:
Name <- c("Name 1","Name 1","Name 1","Name 1","Name 1","Name 2","Name 2","Name 2",
"Name 3","Name 3","Name 3","Name 3","Name 3","Name 4","Name 4","Name 4")
Initial.Value <- c(142, 847, 982, 867, 898, 437, 169, 478,260, 789, 216, 373, 820,
985, 943, 325)
Bonus.1 <- c(4, 2, 5, 0, 9, 6, 6, 7, 5, 8, 5, 5, 5, 8, 8, 8)
Bonus.2 <- c(4, 4, 0, 10, 5, 10, 2, 10, 8, 3, 9, 6, 3, 3, 2, 1)
Bonus.3 <- c(3, 0, 2, 7, 5, 0, 3, 6, 9, 5, 1, 2, 1, 5, 3, 2)
Bonus.4 <- c(1, 10, 2, 3, 2, 5, 7, 5, 3, 1, 6, 10, 3, 4, 7, 9)
data_file <- data.frame(Name, Initial.Value, Bonus.1, Bonus.2, Bonus.3, Bonus.4)
Rows <- unique(data_file$Name)
Output_file <- data.frame(matrix(0, ncol = length(Rows), nrow = 5))
colnames(Output_file) <- Rows
rownames(Output_file) <- colnames(data_file)[c(2,3,4,5,6)]
for(i in length(Rows)){ # Looks at each name in turn
Indices_Of_Interest <- which(lapply(data_file$Name,
function(x) any(match(x, Rows[i]))) == TRUE)
for(k in length(Output_file[, 1])){ # Goes down the Output_File
row_header <- rownames(Output_file)[k]
col_header <- Rows[i]
Output_file[row_header, col_header] <- sum(data_file[row_header][Indices_Of_Interest, ])
}
}
When I run this code line by line it works by updating each cell in turn, but when I run the for loop it seems to only act on the final cell, leaving the other cells as zero, as follows: