Reputation: 687
I have this simple codes for matrix called rates and works well.
thresholds <- c(1e-8,1e-7,1e-6,1e-5,1e-4,1e-3,1e-2,1e-1,1)
rates = matrix(0,2,length(thresholds))
for (i in 1:length(thresholds)) {
rates[1,i] = 1
rates[2,i] = 1
However, when I apply the same idea to a bigger data (matrix), somehow there is an error.
thresholds <- c(1e-8,1e-7,1e-6,1e-5,1e-4,1e-3,1e-2,1e-1,1)
rates = matrix(0,2,length(thresholds))
for (i in 1:length(thresholds)) {
t = thresholds[i]
prob_matrix = solution_matrix(prob_matrix, t)
compare_true_est_sol = compare_solutions(synthetic_solution, prob_matrix)
rates[1,i] = compare_true_est_sol["TP"]/(compare_true_est_sol["TP"]+compare_true_est_sol["FN"])
rates[2,i] = compare_true_est_sol["FP"]/(compare_true_est_sol["FP"]+compare_true_est_sol["TN"])
}
return(rates)
I attach the photo to see the matrix example. The solution_matrix() and compare_solutions() are the function you can ignore. The error is "
Error in rates[2, i] <- compare_true_est_sol["FP"]/(compare_true_est_sol["FP"] + compare_true_est_sol["TN"]) : incorrect number of subscripts on matrix
". Please anyone help why the error happened and how t solve it?
UPDATE: I followed @BrianMontgomery suggestion, and it works for thresholds = c(1) is a vector with one element, but the error happened when I set the thresholds to be a vector with more than one element, such as thresholds = c(1, 2). The error is "Error in if (solution_matrix[i, j] == TRUE) { : missing value where TRUE/FALSE needed". The code for the solution_matrix is as follows.
solution_matrix <- function(probability_matrix, threshold){
probability_matrix = probability_matrix>=threshold
solution_matrix = probability_matrix
for (i in 1:nrow(solution_matrix)){
for (j in 1:ncol(solution_matrix)){
if (solution_matrix[i,j]== TRUE){
solution_matrix[i,j] = i-1
} else {
solution_matrix[i,j] = NA
}
}
}
for (j in 1:ncol(solution_matrix)){
solution_matrix[,j] = sort(as.numeric(solution_matrix[,j]),
na.last = TRUE)
}
solution_matrix = solution_matrix
colnames(solution_matrix) <- gsub("\\.", "-",
colnames(solution_matrix))
return(solution_matrix)
}
Upvotes: 0
Views: 83
Reputation: 687
I have solved the issue. I have tried to make a reproducible example, but it was more difficult than I expected. I solved it by renaming the variable "prob_matrix" to "sol". The error happened because the variable name "prob_matrix" is similar to the parameter name for the solution_matrix(prob_matrix, t) so that the for loop does not work for the second iteration.
Upvotes: 0
Reputation: 2414
You are treating compare_true_est_sol as if it is a vector, but it's a 1 x 4 matrix with the rowname "1".
So either use compare_true_est_sol[1, "FP"]
or make it a vector:
compare_true_est_sol <- unlist(compare_true_est_sol[1, ])
Upvotes: 1