R语言中实现矩阵和三元组的相互转换
001、
1、矩阵转换为三元组
num <- c(5, 2, 7, 0, 9, 3, 4, 2, 3, 1, 7, 8) dat <- matrix(num, nrow = 3, ncol = 4, byrow = T) dat rows <- rep(1:nrow(dat), each = ncol(dat)) ## 行 rows cols <- rep(1:ncol(dat), time = nrow(dat)) ## 列 cols value <- c(t(dat)) ## 值 value result <- data.frame(rows, cols, value) result

2、三元组转换为矩阵 :
result rows <- max(result$rows) cols <- max(result$cols) dat <- matrix(0, nrow = rows, ncol = cols) dat for (i in 1:nrow(result)) { dat[result[i,1], result[i,2]] = result[i,3] ## 三元组转换为矩阵 } dat

002、
1、矩阵转换为三元组
num <- c(5, 2, 7, 0, 9, 3, 4, 2, 3, 1, 7, 8) dat <- matrix(num, nrow = 3, ncol = 4, byrow = T) dat rows <- rep(1:nrow(dat), time = ncol(dat)) rows cols <- rep(1:ncol(dat), each = nrow(dat)) cols values <- as.vector(dat) values result <- data.frame(rows, cols, values) ## 矩阵转换为三元组 result

2、三元组转换为矩阵
dat rows <- max(dat$rows) rows cols <- max(dat$cols) cols result <- matrix(0, nrow = rows, ncol = cols) result for (i in 1:nrow(dat)) { ## 三元组转换为矩阵 result[dat[i,1], dat[i,2]] = dat[i,3] } result

 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号