Re: [問題] txt檔如何直轉橫
我的測試檔案
----------------tmp.txt------------------
name,time,price
A,2000/01/31,-1
A,2000/02/29,2
A,2000/03/31,-3.3
A,2010/12/31,5
E,2000/01/31,-4
E,2000/02/29,5
E,2000/03/31,-1.1
E,2010/12/31,5
Z,2000/01/31,-10
Z,2000/02/29,7
Z,2000/03/31,-1.8
Z,2010/12/31,-2
---------------end of file----------------
R code:
x=read.table("tmp.txt",sep=",", header=TRUE)
x[,3] = abs(x[,3])
x.wide=reshape(x,direction="wide",
v.names=c("price"),
timevar="name",
idvar="time")
output:
time price.A price.E price.Z
1 2000/01/31 -1.0 -4.0 -10.0
2 2000/02/29 2.0 5.0 7.0
3 2000/03/31 -3.3 -1.1 -1.8
4 2010/12/31 5.0 5.0 -2.0
matlab code
---------------new.txt-------------
name time price
A 2000/01/31 -1
A 2000/02/29 2
A 2000/03/31 -3.3
A 2010/12/31 5
E 2000/01/31 -4
E 2000/02/29 5
E 2000/03/31 -1.1
E 2010/12/31 5
Z 2000/01/31 -10
Z 2000/02/29 7
Z 2000/03/31 -1.8
Z 2010/12/31 -2
------------------------------------
new.txt之間是tab,是空白的話,下面'\t'請改成' '
Dat = readtable('new.txt', 'Format', '%s%s%f', 'delimiter', '\t');
Dat.price = abs(Dat.price);
W = unstack(Dat, 'price', 'name');
Matlab的速度很快,可以試試看。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 36.238.81.92
→
11/01 17:44, , 1F
11/01 17:44, 1F
R的code就在上面,只是用sep=",",如果你的間隔是空白就改成sep=" "
※ 編輯: celestialgod 來自: 218.164.79.5 (11/01 19:09)
→
11/02 11:45, , 2F
11/02 11:45, 2F
→
11/02 11:47, , 3F
11/02 11:47, 3F
→
11/03 22:41, , 4F
11/03 22:41, 4F
→
11/03 23:17, , 5F
11/03 23:17, 5F
→
11/04 12:11, , 6F
11/04 12:11, 6F
我改成這樣,結果如下:
x=read.table("test.txt", header=TRUE)
x[,3] = abs(as.numeric(x[,3]))
x.wide=reshape(x,direction="wide",
v.names=c("Adjprc"),
timevar="name",
idvar="time")
> dim(x.wide)
[1] 504 1986
※ 編輯: celestialgod 來自: 36.239.250.66 (11/04 19:03)
→
11/05 20:22, , 7F
11/05 20:22, 7F
推
11/07 22:17, , 8F
11/07 22:17, 8F
推
11/07 22:18, , 9F
11/07 22:18, 9F
→
11/07 22:18, , 10F
11/07 22:18, 10F
→
11/07 22:18, , 11F
11/07 22:18, 11F
→
11/07 22:19, , 12F
11/07 22:19, 12F
→
11/07 22:19, , 13F
11/07 22:19, 13F
→
11/07 22:19, , 14F
11/07 22:19, 14F
討論串 (同標題文章)
R_Language 近期熱門文章
PTT數位生活區 即時熱門文章