Thank you for your help.I'm sorry for the rudimentary question, but I'd appreciate it if you could give me some advice as I haven't been able to solve the problem that takes too much time to calculate large data.
What do you want to do?
v<-c (1, 5, 10, 1, 2, 4)
names(v)<-c("a1_b1", "a1_b8", "a2_b3", "a3_b1", "a3_b2", "a4_b7")
library (Matrix)
mat<- Matrix (0, nrow=4, ncol=8)
ronames(mat)<-paste("a", seq(1,4), sep="")
colnames(mat)<-paste("b", seq(1,8), sep="")
We would like to map this vector v to sparse matrix mat.The result I want is
b1b2b3b4b5b6b7b8
a11. . .5
a2. .10. . .
a31 2. . . .
a4. . . 4.
A matrix similar to .
Initially
① Repeat from a1 to a4 in the for loop
② If i = 1, extract the element corresponding to a1 from v (in this case, c(1,5))
③ Create an empty vector X (additions b1-b8) with 8 elements and 0 values, and map the elements obtained in で to the corresponding subscripts (this time, b1, b8)
④ Convert X to dgCMatrix
⑤ Repeat ~ to を until i=4, and rowbind the created X one after another
I used to do this, but when the data size increases, it doesn't end in real time (in fact, there are 50 million elements of v).
It seems that the part (extraction) of ) takes a lot of time, so I would like to process it together by applying instead of using a for statement, but I can't think of an idea.
I'm sorry for the confusing sentence, but I'd appreciate it if you could help me.
The matrix (array) index can be given a matrix with row values in the first column and column values in the second column.
If you use this, you can use for
to replace the values in bulk, so I think it will speed up.
It's a bit troublesome to index from the name of the vector v, but the code below should work.
library(stringr)
i<-names(v)%>%
str_replace_all(c(a="",b="")%>%
str_split("_")%>%
unlist%>%
as.integer%>%
matrix(ncol=2, byrow=TRUE)
mat[i]<-v
mat
© 2024 OneMinuteCode. All rights reserved.