R adding extra rows in a matrix where row names are unique
Use setdiff
to figure out which rows need to be added, create an empty matrix, and rbind
them together:
toAdd <- setdiff(colnames(mat), rownames(mat))
m <- matrix(0, ncol = ncol(mat), nrow = length(toAdd),
dimnames = list(toAdd, colnames(mat)))
rbind(mat, m)
# a b c d e
# a 1 0 0 1 0
# e 1 0 0 1 0
# b 0 0 0 0 0
# c 0 0 0 0 0
# d 0 0 0 0 0
This assumes "mat" is defined as:
mat <- structure(c(1L, 1L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L),
.Dim = c(2L, 5L),
.Dimnames = list(c("a", "e"), c("a", "b", "c", "d", "e")))
How to save values from matrix to another with keeping columns and rows names unchanged in R?
Something like this should simplify your code and work for you:
# Toy data
data.corr <- cor(matrix(rnorm(200), 20, 10))
rownames(data.corr) <- colnames(data.corr) <- paste0("company", 1:10)
print(data.corr)
# Get highest correlations for each company
COR <- apply(data.corr, 2, sort, decreasing = TRUE)[1:5 + 1, ]
# Get corresponding rows / companies
COR_comp <- apply(data.corr, 2, order, decreasing = TRUE)[1:5 + 1, ]
If you insist that it is the names that appear (and not numbers) that appear in COR_comp
, you can modify it further. For example, the following will fill in the company names:
COR_comp[] <- colnames(COR_comp )[c(COR_comp )]
Create a matrix to be filled in without specifying its dimension
When vector length is known
Here's a solution where you create an empty matrix M
of known dimensions (number of rows is vector length (lVector
) and number of columns (nCols
) you pick yourself). After nCols
(when matrix is full) you write it to a disc with a unique identifier.
# These parameters are known
lVector <- 10
nCols <- 1e4
# Create matrix
M <- matrix(nrow = lVector, ncol = nCols)
iter <- 0
# This is unknown before
nIterations <- 1e5 + 10
# Perform iterations
for(i in seq_len(nIterations)) {
iter <- iter + 1
# Perform simulation and write result to a matrix column
M[, iter] <- sample(100, 10)
if (iter == nCols) {
# Write result to disc
saveRDS(M, paste0("result_", i, ".RDS"))
# Reset counter
iter <- 0
# Create new empty matrix
M <- matrix(nrow = lVector, ncol = nCols)
}
}
# Write last 10 iterations to a disc (they didn't reach 1e4)
saveRDS(M[, 1:iter], paste0("result_", i, ".RDS"))
This will write matrices (result_10000.RDS
, result_20000.RDS
, ...)
When vector length is unknown
Here you can create an empty list of length lList
and after lList
iterations write it to a disc and re-create a new list.
# These parameters are known
lList <- 1e4
iter <- 0
# Create empty list
L <- rep(list(NA), lList)
# This is unknown before
nIterations <- 1e5 + 10
# Perform iterations
for(i in seq_len(nIterations)) {
iter <- iter + 1
L[[iter]] <- sample(100, 10)
if (iter == lList) {
saveRDS(L, paste0("result_", i, ".RDS"))
iter <- 0
L <- rep(list(NA), lList)
}
}
saveRDS(L[1:iter], paste0("result_", i, ".RDS"))
add row and column to matrix based on sequence and fill it with NaN
There was an answer a minute ago, which I believe was a very good one, and I actually came by again to comment on it with some modifications, and up-vote it, but it seems it was deleted
In any case here is the updated version of the mentioned answer
#create matrix with missing column and row
mat_1 = matrix(rnorm(16), nrow=4, ncol=4, byrow = TRUE)
#rename columns and rows
dimnames(mat_1) = list(c("a", "c", "d", "e"), c("a", "c", "d", "e"))
mat_2 <- matrix(
NA,
nrow = length(letters[1:5]),
ncol = length(letters[1:5]),
dimnames = list(letters[1:5], letters[1:5]))
mat_2[rownames(mat_1), colnames(mat_1)] <- mat_1
mat_2
# a b c d e
# a -0.5021924 NA 0.1315312 -0.07891709 0.88678481
# b NA NA NA NA NA
# c 0.1169713 NA 0.3186301 -0.58179068 0.71453271
# d -0.8252594 NA -0.3598621 0.08988614 0.09627446
# e -0.2016340 NA 0.7398405 0.12337950 -0.02931671
Selecting a single row of a named matrix and keeping the row name
Thanks to ZheyuanLi, we can search ?Extract
which gives the options to []
(note that this is different than ?subset
). We realize that there is a drop
argument which does the job of keeping a row matrix: M[1, , drop = FALSE]
.
Here is the relevant part from R-FAQ, again courtesy of ZheyuanLi.
Select a column by column-name, but a different name for each row of a matrix in R?
As the help page ?`[`
says, you can subset with a matrix to get individual elements. Each row of the subsetting matrix is an element, and the columns specify the indices for each dimension.
match(columns,colnames(aMatrix)) #gets the column indices
# [1] 1 5 4
b <- cbind(seq_along(columns),match(columns,colnames(aMatrix))) #subset matrix
# [,1] [,2]
# [1,] 1 1 #first element: first row first column
# [2,] 2 5 #second element: second row fifth column
# [3,] 3 4 #third element: third row fourth column
aMatrix[b]
# [1] 1 14 12
Related Topics
Factor Order Within Faceted Dotplot Using Ggplot2
Create a 24 Hour Vector with 5 Minutes Time Interval in R
Ggplot2 Avoid Boxes Around Legend Symbols
Remove Fill Around Legend Key in Ggplot
Ggplot: Remove Na Factor Level in Legend
Cannot Coerce Type 'Closure' to Vector of Type 'Character'
Format a Date Column in a Data Frame
How to Convert a String in a Function into an Object
How to Open an .Xlsb File in R
How to Set Unique Row and Column Names of a Matrix When Its Dimension Is Unknown
Ggplot2 Equivalent of Matplot():Plot a Matrix/Array by Columns
Use Pipe Without Feeding First Argument
Ggplot Legend Issue W/ Geom_Point and Geom_Text
How to Get the Text Between Two Words in R
Rollmean with Dplyr and Magrittr
How to Generate Bin Frequency Table in R
Using Multiple Ellipses Arguments in R
Why Does Rendering a PDF from Rmarkdown Require Closing Rstudio Between Renders