【问题标题】:simple reshape in R using reshape2 causes error使用 reshape2 在 R 中进行简单整形会导致错误
【发布时间】:2013-05-15 08:43:22
【问题描述】:

我正在尝试做一个简单的reshape 使test 看起来像这样:

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

这是我尝试的代码:

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

这是怎么回事?

> 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

【问题讨论】:

  • 如果目标是从m 恢复test,那么你想要:dcast(m, cf ~ variable, value.var = "value")
  • @G.Grothendieck:不确定我是否遵循,目的是让测试看起来像问题的第二行。
  • 试试这个:dcast(m, 1 ~ cf + variable)

标签: r dataframe reshape reshape2


【解决方案1】:

也许您的问题是您实际上剩下的“行”变量为零(即,您根本不希望在转换公式的 LHS 上有任何东西)。这种解决方法(添加虚拟变量)可能会有所帮助?

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

【讨论】:

  • 我不确定它是技术上的一个错误——人们必须仔细查看规范/文档,看看是否在讨论零变量左案例全部。如果没有提到,那么它是“未定义的行为”而不是错误......(软件没有按照您的意愿行事,在设计者没有考虑的情况下,不一定构成错误。)
【解决方案2】:

这是基本的 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

【讨论】:

  • 谢谢!我希望坚持使用这个包,因为我已经习惯了,但我应该尽可能使用基本 R 功能。
猜你喜欢
  • 1970-01-01
  • 2020-09-30
  • 1970-01-01
  • 1970-01-01
  • 2013-02-20
  • 2012-02-12
  • 1970-01-01
  • 2022-12-01
  • 1970-01-01
相关资源
最近更新 更多