I am trying to populate an array of lists in R . Here is my code TunePar<-matrix(list(Null),2,2) TunePar[1,1]=list(G=2) But when I type TunePar[1,1,], all I get is 2. The G has disappeared. why? If I do this Test=list(G=2)> Test$G [1] 2 [[alternative HTML version deleted]]
Hi, Provide a list of a list in the second assignment: -- TunePar <- matrix(list(NULL), 2, 2) TunePar[2,1] <- list(list(G = 2)) TunePar[2,1] TunePar[2,1][[1]]$G TunePar[[2]]$G --- The point is that "[" returns the list element of the same level as the original object (TunePar in the present example). So in the assignment if you extracted one element on the LHS, it expects a one-element vector on the RHS, e.g., check this out: --- # this throws an error TunePar[1,2] <- list(H = 1:3, I = letters[1:2]) # this is fine TunePar[1,2] <- list(list(H = 1:3, I = letters[1:2])) TunePar[1,2] TunePar[1,2][[1]]$I --- HTH, Denes On 01/22/2016 08:29 AM, TJUN KIAT TEO wrote:> TunePar<-matrix(list(Null),2,2) > > TunePar[1,1]=list(G=2)
On 22/01/2016 2:29 AM, TJUN KIAT TEO wrote:> I am trying to populate an array of lists in R . Here is my code > > TunePar<-matrix(list(Null),2,2) > > TunePar[1,1]=list(G=2) > > But when I type TunePar[1,1,], all I get is 2. The G has disappeared. why? > > If I do this > > Test=list(G=2) >> Test > $G > [1] 2 >Matrices generally don't keep the names of elements assigned to them. What you did is similar to x <- matrix(0, 2,2) x[1,1] <- c(G=2) x which loses the name. Working with lists is different, because you need to distinguish between subsets and elements. So you'd get what you want by assigning your list to the element using TunePar[[1,1]] <- list(G=2) At this point, TunePar[1,1] is a list containing list(G=2): it prints as [[1]] [[1]]$G [1] 1 To get the result you want, you also need to access the element instead of the subset: TunePar[[1,1]] will print $G [1] 1 Duncan Murdoch