使用reshape2在R中简单重塑会导致错误

时间:2021-11-10 22:49:32

I am trying to do a simple reshape to make test look like this:

我正在尝试做一个简单的重塑,使测试看起来像这样:

a_estimate, a_tstat, b_estimate, b_tstat
1,          3,       2,          4

This is the code I try:

这是我尝试的代码:

require(reshape2)
test = data.frame(cf=c("a", "b"), estimate=c(1,2), tstat=c(3,4))
m = melt(test, id.vars="cf")
d = dcast(m, formula = . ~ cf + variable)
Error: nrow(res$labels[[1]]) == nrow(data) is not TRUE

What's going on here?

这里发生了什么?

> sessionInfo()    
R version 2.15.2 (2012-10-26)
Platform: x86_64-unknown-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=C                 LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
 [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
 [1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] reshape2_1.2.2

loaded via a namespace (and not attached):
 [1] plyr_1.8      stringr_0.6.2

2 个解决方案

#1


6  

Maybe your problem is that you have effectively zero "row" variables left (i.e., you don't want anything at all on the LHS of the casting formula). This workaround (adding a dummy variable) might help?

也许你的问题是你有效地留下零“行”变量(也就是说,在铸造公式的LHS上你根本不需要任何东西)。这种解决方法(添加虚拟变量)可能会有所帮助吗?

d = dcast(cbind(x=1,m), formula = x ~ cf + variable)

#2


5  

Here's the base R way, for fun...

这是基本的R方式,为了好玩......

reshape(transform(test, id=1), idvar='id', timevar='cf', direction='wide')[-1]
#   estimate.a tstat.a estimate.b tstat.b
# 1          1       3          2       4

#1


6  

Maybe your problem is that you have effectively zero "row" variables left (i.e., you don't want anything at all on the LHS of the casting formula). This workaround (adding a dummy variable) might help?

也许你的问题是你有效地留下零“行”变量(也就是说,在铸造公式的LHS上你根本不需要任何东西)。这种解决方法(添加虚拟变量)可能会有所帮助吗?

d = dcast(cbind(x=1,m), formula = x ~ cf + variable)

#2


5  

Here's the base R way, for fun...

这是基本的R方式,为了好玩......

reshape(transform(test, id=1), idvar='id', timevar='cf', direction='wide')[-1]
#   estimate.a tstat.a estimate.b tstat.b
# 1          1       3          2       4