Question

I have a for loop that stores in a list one date and one value after some computations. I would like to create a two-column table (date,value) but when I extract the values from the list I can't preserve the date format:

n <- 5

x <- factor(1:3,levels=1:3,labels=c('a','b','c'))
dates <- as.Date(c('2000-01-01','2001-01-01','2002-01-01'))

mylist <- list()

for (i in 1:n) {

  #Some operations

  mylist[[i]] <- list(sample(dates,1),as.numeric(sample(x,1)))

}

z <- do.call(cbind,mylist)
Was it helpful?

Solution

You need to change the data structure to one that can actually hold different data types (i.e. a data frame) and then rbind them together:

for (i in 1:n) {

  #Some operations

  mylist[[i]] <- data.frame(sample(dates,1),as.numeric(sample(x,1)))

}

z <- do.call(rbind,mylist)

The problem in your code was that the cbind operation coerced the list to a matrix (which is the default behavior of rbind/cbind) which can only hold one data type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top