Brian
Brian

Reputation: 7326

Problems creating list of lists in R

I have been trying to create a list of lists in R. I start by creating a list of lists of prespecified length. I then iterate through a matrix using a for loop to fill the lists.

The problem is that I seem to be getting lists of lists of lists etc.

My code:

potential_dups <- rep(list(list()), 10)
nearest10 <- matrix(rnorm(100), nrow=10)

for (i in 1:length(nearest10[ , 1])) {
  for (j in 1:10) {
    if (nearest10[i, j] < 0.35 && nearest10[i, j] > 0) {
      potential_dups[[i]] <- append(potential_dups[[i]], nearest10[i, j])
    }
  } 
}  

Why is this happening? How can I create a lists of this format?

[[1]]
[1] "Element 1A"
[[1]]
[2] "Element 1B"
[[1]]
[3] "Element 1C"

[[2]]
[1] "Element 2A"
[[2]]
[2] "Element 2B"

Additionally, I am ending up with empty list that are displayed for example as: [[3]] list() There first elements are NULL. I would additionally like to write script that subsets out only the non-empty lists from this data structure.

Upvotes: 0

Views: 6391

Answers (2)

Roland
Roland

Reputation: 132651

Here is a nicer (better readable and more efficient) way:

mat <- nearest10
mat[mat >= 0.35 | mat <= 0] <- NA
potential_dups <- apply(mat,1,function(x) as.list(na.omit(x)))

However, I can't imagine why you want this output. It doesn't seem the most useful. maybe you could use the following instead?

potential_dups <- apply(mat,1,function(x) c(na.omit(x)))

Upvotes: 0

user2568961
user2568961

Reputation: 74

Altough your example isn't reproducible, I get a list of lists with the following similar code:

potential_dups <- rep(list(list()), 10)
nearest10 <- matrix(rnorm(100), nrow=10)
for (i in 1:10) {
  for (j in 1:10) {
    if (nearest10[i, j] < 0.35 & nearest10[i, j] > 0) {
      potential_dups[[i]] <- append(potential_dups[[i]], nearest10[i, j])
    }
  } 
}  

To remove empty lists you can do this:

potential_dups[sapply(potential_dups, function(x) length(x) > 0)]

Upvotes: 1

Related Questions