[R] Accessing matrix elements within a list
jim holtman
jholtman at gmail.com
Sat Jun 26 13:52:47 CEST 2010
first of all take a look at the object you created:
> df.list <- vector("list", 3)
>
>
> for(i in 1:3){
+ assign(paste("s",i, sep=""),matrix(0, nrow = 20, ncol = 5, byrow
+ = FALSE, dimnames = NULL))
+ }
>
> # and then insert them with a loop like this
>
> # put matrices names in a vector
> matrices<-c("s1","s2","s3")
>
> # insert
> for(i in 1:3){
+ df.list[[i]] <- matrices[i]
+ }
>
>
> str(df.list)
List of 3
$ : chr "s1"
$ : chr "s2"
$ : chr "s3"
>
you will see that it is a list of characters since that is what is in
'matrices' What you need to do is to use 'get':
> df.list <- vector("list", 3)
>
>
> for(i in 1:3){
+ assign(paste("s",i, sep=""),matrix(0, nrow = 20, ncol = 5, byrow
+ = FALSE, dimnames = NULL))
+ }
>
> # and then insert them with a loop like this
>
> # put matrices names in a vector
> matrices<-c("s1","s2","s3")
>
> # insert
> for(i in 1:3){
+ df.list[[i]] <- get(matrices[i])
+ }
>
>
> str(df.list)
List of 3
$ : num [1:20, 1:5] 0 0 0 0 0 0 0 0 0 0 ...
$ : num [1:20, 1:5] 0 0 0 0 0 0 0 0 0 0 ...
$ : num [1:20, 1:5] 0 0 0 0 0 0 0 0 0 0 ...
> df.list[[1]][1,]
[1] 0 0 0 0 0
>
or even better just put them in the list at the first:
> df.list <- vector("list", 3)
>
>
> for(i in 1:3){
+ df.list[[i]] <- matrix(0, nrow = 20, ncol = 5, byrow
+ = FALSE, dimnames = NULL)
+ }
>
> str(df.list)
List of 3
$ : num [1:20, 1:5] 0 0 0 0 0 0 0 0 0 0 ...
$ : num [1:20, 1:5] 0 0 0 0 0 0 0 0 0 0 ...
$ : num [1:20, 1:5] 0 0 0 0 0 0 0 0 0 0 ...
> df.list[[1]][1,]
[1] 0 0 0 0 0
>
On Fri, Jun 25, 2010 at 5:29 PM, Maria P Petrova
<mpetrova at u.washington.edu> wrote:
> Hi there,
>
> I cannot seem to figure out how to access the elements of a list if those elements are a matrix.
> For example I have a the following list
>
> df.list <- vector("list", 3)
> and I have made each of the elements a matrix as follows
>
> for(i in 1:3){
> assign(paste("s",i, sep=""),matrix(0, nrow = 20, ncol = 5, byrow
> = FALSE, dimnames = NULL))
> }
>
> # and then insert them with a loop like this
>
> # put matrices names in a vector
> matrices<-c("s1","s2","s3")
>
> # insert
> for(i in 1:3){
> df.list[[i]] <- matrices[i]
> }
>
> My question is I cannot access the first rwo of the matrix within a list. The following does not work
>
> df.list [[1]][1,]
>
> Thanks for your help!
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
--
Jim Holtman
Cincinnati, OH
+1 513 646 9390
What is the problem that you are trying to solve?
More information about the R-help
mailing list