举个例子,假设我有以下数据帧:
datas=data.frame(Variables=c("Power","Happiness","Power","Happiness"),
Country=c("France", "France", "UK", "UK"), y2000=c(1213,1872,1726,2234), y2001=c(1234,2345,6433,9082))
导致以下输出:
Variables Country 2000 2001
1 Power France 1213 1234
2 Happiness France 1872 2345
3 Power UK 1726 6433
4 Happiness UK 2234 9082
我想重塑这个数据帧如下:
Year Country Power Happiness
1 2000 France 1213 1872
2 2001 France 1234 2345
3 2000 UK 1726 2234
4 2001 UK 6433 9082
我开始时:
q2=cast(datas, Country~Variables, value="2000")
但后来出现了以下错误:
Aggregation requires fun.aggregate: length used as default
Error in `[.data.frame`(sort_df(data, variables), , c(variables, "value"), :
undefined columns selected
有什么建议?另外:我的数据帧真的很大(417120乘62)解决方案是否重要?
2 回答
也许你对
tidyverse
替代感兴趣或使用
reshape2::melt
和reshape2::dcast
或(相同)使用
data.table::melt
和data.table::dcast
在性能/运行时方面,我认为
data.table
或tidyr
解决方案是最有效的 . 您可以通过在某些较大的样本数据上运行microbenchmark
来进行检查 .样本数据
基准分析
根据(略微)更大的
78x22
样本数据集对四种方法进行分析后得出结果 .如上所述,我强烈建议使用
tidyr
而不是reshape
,或者至少使用reshape2
而不是reshape
,因为它修复了reshape
的许多性能问题 .在
reshape
本身,你必须首先融化datas
然后根据需要重命名和转换列 .
在
reshape2
中,代码是相同的,但您可以使用dcast
而不是cast
.tidyr
,如@Maurits Evers上面的解决方案是一个更好的解决方案,大多数开发已从reshape2
转移到tidyverse