문제

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)
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top