我想将ts
对象转换为data.frame
对象。我的MWE如下:
set.seed(12345)
dat <- ts(data=runif(n=10, min=50, max=100), frequency = 4, start = c(1959, 2))
library(reshape2)
df <- data.frame(date=as.Date(index(dat)), Y = melt(dat)$value)
date Y
1 1975-05-14 86.04519
2 1975-05-14 93.78866
3 1975-05-14 88.04912
4 1975-05-15 94.30623
5 1975-05-15 72.82405
6 1975-05-15 58.31859
7 1975-05-15 66.25477
8 1975-05-16 75.46122
9 1975-05-16 86.38526
10 1975-05-16 99.48685
我在日期栏中丢失了我的宿舍。如果您能帮助解决问题,我将非常感谢。提前谢谢。
答案 0 :(得分:30)
怎么样
data.frame(Y=as.matrix(dat), date=time(dat))
返回
Y date
1 86.04519 1959.25
2 93.78866 1959.50
3 88.04912 1959.75
4 94.30623 1960.00
5 72.82405 1960.25
6 58.31859 1960.50
7 66.25477 1960.75
8 75.46122 1961.00
9 86.38526 1961.25
10 99.48685 1961.50
答案 1 :(得分:11)
zoo
(来自Date
)允许创建> dat <- ts(data=runif(n=10, min=50, max=100), frequency = 4, start = c(1959, 2))
> data.frame(Y=as.matrix(dat), date=as.Date(as.yearmon(time(dat))))
Y date
1 51.72677 1959-04-01
2 57.61867 1959-07-01
3 86.78425 1959-10-01
4 50.05683 1960-01-01
5 69.56017 1960-04-01
6 73.12473 1960-07-01
7 69.40720 1960-10-01
8 70.12426 1961-01-01
9 58.94818 1961-04-01
10 97.58294 1961-07-01
个对象。
{{1}}
答案 2 :(得分:6)
包timetk有几个转换函数。在你的情况下:
interface Constructor<M> {
new (...args: any[]): M
}
class Base {
static foo<T extends Base>(this: Constructor<T>): T {
return new this()
}
}
class Subclass extends Base {
readonly bar = 1
}
// Prove we have a Subclass instance by invoking a subclass-specific method:
Subclass.foo().bar
答案 3 :(得分:1)
似乎从xts
对象进行转换似乎既可靠又有据可查。下面的方法在date / yearqtr类中具有新的date列。
library(xts)
datx <- as.xts(dat)
df <- data.frame(date=index(datx), coredata(datx))
检查date
的班级:
class(df$date)
[1] "yearqtr"
结果:
print(df)
date coredata.datx.
1 1959 Q2 86.04519
2 1959 Q3 93.78866
3 1959 Q4 88.04912
4 1960 Q1 94.30623
5 1960 Q2 72.82405
6 1960 Q3 58.31859
7 1960 Q4 66.25477
8 1961 Q1 75.46122
9 1961 Q2 86.38526
10 1961 Q3 99.48685