Thursday, 15 September 2011

r - reading indices and values of a matrix from a file and assigning the value -



r - reading indices and values of a matrix from a file and assigning the value -

say have file 3 columns. first 2 columns indices(row,column) of matrix. 3rd value need store in matrix. first 5 lines of file looks this.

v1 v2 v3 [1,] 13 14 4950 [2,] 20 50 4949 [3,] 22 98 4948 [4,] 30 58 4947 [5,] 43 48 4946

say read file next command:

idx<-as.matrix(read.table("data.txt"))

i create matrix b , store in there code doesn't seem work. found work around using loop seems work fine takes long time.

b<-matrix(0,100,100) b[idx[,1],idx[,2]]<-idx[,3]

when seek next get:

> b[13,14] [1] 126 > b[22,98] [1] 115

which doesn't match 3rd column. sorry if simple question. going on here?

you might consider scan reading matrices. result, outputs message number of lines read. can build new matrix.

> s <- scan("data.txt") # read 15 items > m <- matrix(s, 15/3, 3, byrow = true) > b <- matrix(0, 100, 100) > b[ m[, 1], m[, 2] ] <- m[, 3] > b[13, 14] # [1] 4950 > b[22, 98] # [1] 4948

r matrix

No comments:

Post a Comment