我看到这个问题已经问了很多遍了,我本人尝试了所有将因子转换为数值的方法,包括:
as.numeric(as.character(x))
lapply(x, function(y) as.numeric(levels(y))[y])
as.numeric.factor <- function(y) as.numeric(levels(y))[y]
lapply(x, as.numeric.factor)
我不能使用unlist
函数,因为我想要宽格式的输出,而unlist
将其转换为long。
但是所有这些都给出了NA值作为输出。
当我特别检查x时,它会适当显示值。
> class(x)
[1] "data.frame"
> class(x$Col2)
[1] "factor"
> class(x$Col1)
[1] "Date"
请找到可复制的示例:
set.seed(354)
df <- data.frame(Product_Id = rep(1:100, each = 50),
Date = seq(from = as.Date("2014/1/1"), to = as.Date("2018/2/1") , by = "month"),
Sales = rnorm(100, mean = 50, sd= 20))
df <- df[-c(251:256, 301:312, 2551:2562, 2651:2662, 2751:2762), ]
library(zoo)
z <- read.zoo(df, index = "Date", split = "Product_Id", FUN = as.yearmon)
tt <- as.ts(z)
fcast <- matrix(NA, ncol = ncol(tt), nrow = 12)
library(forecast)
for(i in 1:ncol(tt)){
fc1 <- forecast(stlf(na.trim(tt[,i]),h=12))
fcast[,i] <-fc1$mean
}
forecasted <- format(round(rbind(tt, fcast),2),nsmall = 2)
dd <- data.frame(date = seq(as.Date('2014-01-01'), by = 'months', length = nrow(forecasted)),Prod_Id = forecasted)
dd_f <- lapply(dd, function(x) as.numeric(levels(x))[x])
关于我可能会缺少什么的任何建议?