loops - R: Apply family that deletes columns as part of the function -


i trying iterate through each row in matrix, find column minimum value , column name , delete column after has been used new minimum can calculated. correct answer should this:

result 1/1   50 2/2   61 3/3   72 4/4   83  test_matrix <- matrix(c(50:149), ncol = 10 , byrow=false)  names <- c(1:10)  colnames(test_matrix) <- names  rownames(test_matrix) <- names   result <- t(sapply(seq(nrow(test_matrix)), function(i) {   j <- which.min(test_matrix[i,])   c(paste(rownames(test_matrix)[i], colnames(test_matrix)[j], sep='/'), test_matrix[i,j])   drops <- colnames(test_matrix)[j]   test_matrix[ , !(names(test_matrix) %in% drops)] })) result 

second question choose order of rows during iteration chooses go next row had same name column name. example, if column minimum named 5, column 5 deleted , minimum row named 5 calculated next.

wondering if possible , if loop needed these calculations.

as new r user, appreciate help. thanks!

for first part of question:

test_matrix <- matrix(c(50:149), ncol = 10 , byrow=false) names <- c(1:10) colnames(test_matrix) <- names rownames(test_matrix) <- names  result <- matrix(nrow=0, ncol=2)  (i in 1:nrow(test_matrix)) {   test_matrix <- as.matrix(test_matrix) #when test_matrix has 1 column r converts vector   j <- which.min(test_matrix[i, ])   result <- rbind(result, c(paste(rownames(test_matrix)[i],                                    colnames(test_matrix)[j], sep='/'),                              as.numeric(test_matrix[i,j])))   test_matrix <- test_matrix[, -j] #remove column j }  result ##      [,1]  [,2]  ## [1,] "1/1" "50"  ## [2,] "2/2" "61"  ## [3,] "3/3" "72"  ## [4,] "4/4" "83"  ## [5,] "5/5" "94"  ## [6,] "6/6" "105" ## [7,] "7/7" "116" ## [8,] "8/8" "127" ## [9,] "9/9" "138" ##[10,] "10/" "149" 

edit: second part, instead of for loop, can use this:

i <- 1 while(length(test_matrix)>0) {   test_matrix <- as.matrix(test_matrix)   j <- which.min(test_matrix[i, ])   result <- rbind(result, c(paste(rownames(test_matrix)[i],                                    colnames(test_matrix)[j], sep='/'),                              as.numeric(test_matrix[i,j])))   test_matrix <- test_matrix[, -j]   <- as.numeric(names(j))+1 } 

Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo