R reshape2中的自定义变量名称

时间:2013-04-09 19:31:05

标签: r reshape2

有没有办法改变dcast函数命名变量的默认方式?例如

require(reshape2)
x = data.frame(id=1:2, t=1:5, v=10:1)
m = melt(x, id.vars = c("id", "t"))
cx = dcast(m,  t ~ variable + id)
print(cx)

#  t v_1 v_2
#1 1  10   5
#2 2   4   9
#3 3   8   3
#4 4   2   7
#5 5   6   1

我希望v_1名为v_id_1或其他。

1 个答案:

答案 0 :(得分:2)

我认为不可能使用dcast,但你可以像这样使用gsub

 colnames(cx) <- gsub('(.*)_(*.)','\\1_id_\\2',colnames(cx))
> cx
  t v_id_1 v_id_2
1 1     10      5
2 2      4      9
3 3      8      3
4 4      2      7
5 5      6      1