s-news
[Top] [All Lists]

Use of diag() with lapply

To: splus list <s-news@wubios.wustl.edu>
Subject: Use of diag() with lapply
From: Alastair Dempster <demp2979@mach1.wlu.ca>
Date: Wed, 25 Apr 2001 12:24:48 -0400
Organization: Wilfrid Laurier University
This is a beginner question but suggestions would be appreciated.  I
have a list object called 'a' whose components are matrices.  I
would like to zero the diagonals of each matrix (ie. do a
replacement).  I can accomplish the task with a for loop but it
defeats the purpose of having a function like lapply!  How do I get
diag() to be executed on each component of my list?

I have tried the following:

lapply(a, diag(a)<-0)     #Error - can only replace diagonal of
matrix.  This makes sense because I am attempting to apply diag to a
list.

I thought if lapply passed the component to the function, this would
work:
lapply(a, diag([ i ])<-0)    # Parsing error llegal use of [
lapply(a, diag([[ i ] ])<-0) # Parsing error llegal use of [[

Then I thought perhaps I had to explicitly refer to 'a' :
lapply(a, diag(a[ ])<-0)    #Error in "diag<-.default"(.A0, .A1):
Can only replace the diagonal of a matrix
lapply(a, diag(a[[ ]])<-0)  #Error in "diag<-.default"(.A0, .A1):
Can only replace the diagonal of a matrix
Based on the error message I think the above might have been trying
to replace all elements of the matrix.


Thank you,


Alastair Dempster

Grad Student
Dept. Geography and Env. Science
Wilfrid Laurier University
Waterloo, Ontario
Canada


<Prev in Thread] Current Thread [Next in Thread>
  • Use of diag() with lapply, Alastair Dempster <=