I have a preallocated matrix in R and need to fill it with data from a dataframe generated from a file having following format:
1-1-7
1-3-2
2-2-6
1-4-8
....
where the first column contains a row index, the second a column index, and the 3rd contains the values.
Is there a faster/better way then the following loop?
for(i in 1:nrow(file)){
matrix[file[i,1],file[i,2]]=file[i,3]
}
Use
row/col
index as the first and second columns offile
and assign thefile[,3]
tom1
using those index.As I mentioned above, we assign the values based on the row/column index. If we take the first two columns and convert to matrix, the first column acts as the row index and second as the column index
If we subset the
m1
based on the first row i.e.1 1
, we are getting the element ofm1
at row=1 and column=1, similarly for the 2nd row, it would be the element at row=1 and column=3, and so on.. Here, we created a matrix of0
with the specified dimensions. So, the 4 values based on the row/columns positions will be0
Now, we are changing/replacing the values in 'm1' at the specified row/column positions by assigning the value to the 3rd column of 'file'
If we check the values at the specified position, it will be replaced
Or we can use another approach using
sparseMatrix
fromlibrary(Matrix)
data