[R] How to Populate List
Rolf Turner
r.turner at auckland.ac.nz
Sun Jul 12 02:59:22 CEST 2009
On 10/07/2009, at 5:25 PM, Gaurav Kumar wrote:
> Hi Rolf,
>
> My apologies for the inconvenience caused due to my reply @ "R-
> help diges".
> Thanks for providing me a clue to solve the problem .
>
> I modify a bit to populate a list. This is throwing an error
> ##### Error in `*tmp*`[[j]] : subscript out of bounds"
>
> myData <- read.table("table.data",
> header=T,
> sep="\t",
> comment.char = "#"
> );
> inp <- scan("table.data", what=list(comp=" ", A="", B="", C=""));
> n <- c(0:length(inp$comp));
> myList=list();
> for(i in n-1)
> {
> if(i < length(inp$comp))
> {
> j=i+1;
> myList[[j]][1] <-c(as.numeric(myData$A[i]));
> myList[[j]][2] <-c(as.numeric(myData$B[i]));
> myList[[j]][2] <-c(as.numeric(myData$C[i]));
> }
>
> }
> print(myList);
>
> Any idea where i'm doing a mistake which is causing this error.
When you're having difficulty, construct a very simple example that
reproduces
the problem. E.g.
myList <- list()
for(i in 1:10) {
myList[[i]][1] <- 42
}
You'll get the same ``subscript out of bounds'' error. Now
***think*** a bit!!!
Strangely enough ( :-) ) the error message means ***exactly*** what
it says.
The subscript is out of bounds! You are trying to assign a value to
the 1st,
and 2nd, and ... 2nd, but I guess you mean the 3rd, components of
myList[[j]].
But at this stage myList[[j]] ***DOESN'T HAVE ANY COMPONENTS***. It
doesn't exist
yet. How could it have components?
There are a couple of ways you could go to do it right.
(1) (Sticking with your original syntax, more or less.)
if(i < length(inp$comp))
{
j=i+1;
myList[[j]] <- numeric(3) # Now myList[[j]] ***does*** have
components, and all is well.
myList[[j]][1] <- as.numeric(myData$A[i])
myList[[j]][2] <- as.numeric(myData$B[i])
myList[[j]][2] <- as.numeric(myData$C[i])
}
NOTE: The ``c()'' construction you were using is unnecessary and
confusing. What on earth
do you think ``c()'' means, anyway? Also the semicolons are
unnecessary and confusing.
This is ***R*** not SAS or C!!!
(2) (Better.)
if(i < length(inp$comp))
{
j=i+1;
myList[[j]] <- c(as.numeric(myData$A[i]),
as.numeric(myData$B[i]),
as.numeric(myData$C[i]))
}
NOTE: The foregoing is an ***appropriate*** use of ``c()''!!!
cheers,
Rolf
######################################################################
Attention:\ This e-mail message is privileged and confid...{{dropped:9}}
More information about the R-help
mailing list