[R] write to M, using row and columns taken from A and B, with values from C

David Winsemius dwinsemius at comcast.net
Thu Apr 26 14:45:02 CEST 2012


On Apr 26, 2012, at 4:25 AM, Amen wrote:

> I want to write to M, using row and columns taken from A and B, with  
> values
> from C. C is a lot longer than A  and B, so only the first 67420  
> elements of
> C are used in my loop.So how can I improve it to take then the next  
> 67420
> and write it to new file and so on till the 248th 67420. Many thanks
>
>
> library(Matrix)
> M <- Matrix(-9999, 360, 720)   ## creat matrix with 720 columns and  
> 360 ro
> ws with valus of -9999
> long <- file("C:\\New folder (5)\\inra.bin", "rb")
> A = readBin(long, integer(), size = 2, n = 1*67420, signed = TRUE)
> lot <- file("C:\\New folder (5)\\lat.img", "rb")
> B = readBin(lot, integer(), size = 2, n = 1*67420, signed = TRUE)
>  wind <- file("C:\\Wind_WFD_200201.bin", "rb")
>   C= readBin(wind, integer(), size = 2, n = 248*67420, signed =  
> TRUE)  ##it
> has 67420 columns  and 248 rows
>  for (i in seq_along(C)){
>  for (i in (1:67420)) {
>   M(A(i), B(i)) = C(i)

You cannot use parens for such an assignment, since A, B and C are not  
R functions (or mathematical ones even.) You need the '[<-' function  
and its cbind form of arguments. Read ?'[<-'

It is possible to construct an assignment (without a loop) of the form:

# M needs to exist but you did pre-allocate it.
M[ cbind(A, B) ] <- C

However, C does need to be of the same length as A and B for this to  
succeed. At the moment C appears to be too large (by a factor of 248)  
and not of the right dimension for there to be a 1-1 correspondence  
between the C values and the (A,B) pairs.


>  }}
> for (i in seq_along(M)){
> fileName <- sprintf("C:/New folder/glo_%d.flt", i)

Now that does seem strange. Do you really mean to create aew file for  
every single value in M???

> writeBin(as.double(M[[i]]),

Wait! "[[" is for lists. M is a matrix.

> fileName, size = 4)} ## for writing each row to
> to a new file

I think you need to go back and review basic R syntax, and then review  
your code and check for the correspondence of object dimensions and  
the semantics of your assignment goals. As outlines in the Posign  
Guide. You will get further along and get better tyested advice if you  
construct a small test case before sending the question to r-help. The  
error messages at the console _are_ very informative, but if they are  
uncler you should copy them in full in your next posting.

-- 
David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list