Error in `*tmp*`[[i]]: for loop error in creating nested list in R

Viewed 46

I am getting this error: Error in *tmp*[[i]] : subscript out of bounds

When I run a code that iterates through i and j.

Example data below:

#Make example data
A1 <- rnorm(1:100, mean = 10, sd = 1)
B1 <- rep(c(2, 4, 5, 7), each = 25)
AB1 <- rbind(A1, B1)
colnames(AB1) <-  rep(c("A","b"), each = 50)

A2 <- rnorm(1:100, mean = 50, sd = 1)
B2 <- rep(c(2, 4, 5, 7), each = 25)
AB2 <- rbind(A2, B2)
colnames(AB2) <-  rep(c("A","b"), each = 50)

A3 <- rnorm(1:100, mean = 100, sd = 1)
B3 <- rep(c(2, 4, 5, 7), each = 25)
AB3 <- rbind(A2, B2)
colnames(AB3) <-  rep(c("A","b"), each = 50)

data <- list(AB1, AB2, AB3)

# for loop showing error
histlist = NULL
for (i in seq_along(data)) {
  columns <- unique(colnames(data[[i]]))
  for (j in columns) {
    columnsub <- data[[i]][, c(rep(c("A"), each = 50))]
    histlist[[i]][[j]] <- hist(columnsub) #error from this line
  }
} 

I want the loop to create histlist with each i as a nested list having A and B with a nested hist() values. Basically, what you see in histlist after the first iteration.

Any help is greatly appreciated

2 Answers

You can do this with nested lapply call which will generate nested list automatically.

histlist <- lapply(data, function(x) {
  cols <- unique(colnames(x))
  lapply(cols, function(y) hist(x[, colnames(x) == y]))
})

We can correct the issue by turning histlist = NULL to :

histlist = vector('list', length(data))

This will pre-allocate a vector and allow for assigning to the list correctly.

Related