以下不起作用吗?
dcast(d, id ~ time)
# Using var as value column: use value.var to override.
# id 1 2 3
# 1 1 0.2869739 0.59591690 0.8989719
# 2 2 0.4533770 0.14741778 NA
# 3 3 0.1286770 0.02465634 0.7363114
## OR, to get rid of the message:
## dcast(d, id ~ time, value.var = "var")
不过,我怀疑您在问一些不同的问题(如我的评论中所述)。特别是,如果您从以下内容开始:
set.seed(1)
d <- data.frame(id = c(1,1,1,2,2,3,3,3),
time = c(1,2,3,1,2,1,2,3),
var1 = runif(8),
var2 = runif(8))
使用 base R's reshape
,它只是一行:
reshape(d, direction = "wide", idvar = "id", timevar = "time")
# id var1.1 var2.1 var1.2 var2.2 var1.3 var2.3
# 1 1 0.2655087 0.6291140 0.3721239 0.06178627 0.5728534 0.2059746
# 4 2 0.9082078 0.1765568 0.2016819 0.68702285 NA NA
# 6 3 0.8983897 0.3841037 0.9446753 0.76984142 0.6607978 0.4976992
dcast
让我们从“reshape2”中尝试相同的操作。以下是我们可能会采取的方法:
library(reshape2)
dcast(d, id ~ time)
# Using var2 as value column: use value.var to override.
# id 1 2 3
# 1 1 0.6291140 0.06178627 0.2059746
# 2 2 0.1765568 0.68702285 NA
# 3 3 0.3841037 0.76984142 0.4976992
但这不起作用,因为dcast
需要一个value.var
. 所以,我们需要melt
再次获取数据。
d2 <- melt(d, id.vars = c("id", "time"))
head(d2)
# id time variable value
# 1 1 1 var1 0.2655087
# 2 1 2 var1 0.3721239
# 3 1 3 var1 0.5728534
# 4 2 1 var1 0.9082078
# 5 2 2 var1 0.2016819
# 6 3 1 var1 0.8983897
现在,我们可以dcast
很容易地使用了。
dcast(d2, id ~ variable + time)
# id var1_1 var1_2 var1_3 var2_1 var2_2 var2_3
# 1 1 0.2655087 0.3721239 0.5728534 0.6291140 0.06178627 0.2059746
# 2 2 0.9082078 0.2016819 NA 0.1765568 0.68702285 NA
# 3 3 0.8983897 0.9446753 0.6607978 0.3841037 0.76984142 0.4976992