Reputation: 541
I have two matrix, same size, 2 million rows and 2 columns.
matrix_a
has values, while matrix_b
is blank, the value of matrix_b
will be decided by the vaule in matrix_a
.
matrix_b <- matrix(, nrow(matrix_a),2)
for(rows in 1:nrow(matrix_a)){
if (matrix_a[rows,1]==0){
.....do something get values of x,
matrix_b[rows,2] = x
}
else {
do sth else get value of y,
then set matrix_b
}
}
First, how can I speed up this loop, as there are 2 millions rows, it is very slow to process.
Second, I noticed when I tried to simply copy one value from matrix_a
to matrix_b
, it seems does not work. For example, while in my data
matrix_a[1,1] = 'user1'
after I copy the values as
matrix_b[1,1] = matrix_a[1,1]
however, the result turns on as
matrix_b[1,1]='1'
How come? Why the values 'user1' did not set to matrix_b
?
I just found out this might be related to the sorting, as I sort my data first to generate matrix_a
. The value '1' here means the first row after sorting, but I still do not know how it ends up in matrix_b
.
Upvotes: 2
Views: 5372
Reputation: 263332
If the two "somethings" and "somethings-else" can be encapsulated into functions that deliver a vector of the same length as matrix_a[ ,1]
, you could construct the vectors, sth_a
and sth_b
and then run
matrix_b[ , 2] <- ifelse(matrix_a[ ,1] == 0, sth_a , sth_b)
Upvotes: 2