21-Oct 28-Oct 4-Nov 11-Nov
22-Apr 90 95 95 95
29-Apr 95 100 100 100
6-May 95 100 100 100
13-May 90 100 100 95
20-May 90 95 95 90
27-May 80 85 85 90
3-Jun 75 80 80 85
` The data above shows the start dates (rows) and end dates (columns) and values represent outcomes in percentage terms given start and end dates. I want to create an optimization model such that selecting start date and end date produces an outcome using R.
The key to this question is how to subset the data frame based on row and column names. Here I designed a function to achieve this. To use this function, you can set start
to the start date, end
to the end date, and dt
to your data frame.
outcome <- function(start, end, dt){
out <- dt[rownames(dt) %in% start, colnames(dt) %in% end]
return(out)
}
# Example:
outcome(start = "29-Apr", end = "28-Oct", dt = dat)
# [1] 100
Or as mentioned in the comment, you can do the following directly.
outcome <- function(start, end, dt){
out <- dt[start, end]
return(out)
}
DATA
dat <- read.table(text = "'22-Apr' 90 95 95 95
'29-Apr' 95 100 100 100
'6-May' 95 100 100 100
'13-May' 90 100 100 95
'20-May' 90 95 95 90
'27-May' 80 85 85 90
'3-Jun' 75 80 80 85", header = FALSE, row.names = 1)
names(dat) <- c("21-Oct", "28-Oct", "4-Nov", "11-Nov")
@RonakShah Thanks. I have updated my answer based on your comment.