R 如何使用扩展函数获得与cast()等价的结果
我被告知,R 如何使用扩展函数获得与cast()等价的结果,r,casting,reshape,tidyr,spread,R,Casting,Reshape,Tidyr,Spread,我被告知,重塑包已经很长时间没有被积极维护了;另外,我注意到在我的例子中,从cast()函数得出的数字不准确,因此现在我正在研究tidyr包中的spread()函数。我已经看过很多例子,但我仍然不知道如何使用它。有人能帮我解释一下吗 我的数据由多个变量组成,其中,等级、日期、和收入是我想重塑为另一个数据框架的三个变量 最初,我是想 cast(mydata, Grade ~ Date, value= "Revenue", sum) 看看每个年级总共挣多少钱 结果以如下所示的格式显示,但数字完全不
重塑
包已经很长时间没有被积极维护了;另外,我注意到在我的例子中,从cast()
函数得出的数字不准确,因此现在我正在研究tidyr
包中的spread()
函数。我已经看过很多例子,但我仍然不知道如何使用它。有人能帮我解释一下吗
我的数据由多个变量组成,其中,等级、日期、和收入是我想重塑为另一个数据框架的三个变量
最初,我是想
cast(mydata, Grade ~ Date, value= "Revenue", sum)
看看每个年级总共挣多少钱
结果以如下所示的格式显示,但数字完全不正确
> head(mydata)
Grade 001.2020 1. Period 2020 002.2020 2. Period 2020 003.2020 3. Period 2020 004.2020 4. Period 2020
1 5160 Brne 0 3773 0 0
2 5305 Vleipner 871751 872116 790616 1086088
3 5315 Digor 282535 232953 368555 218094
4 5329 Yverker 21 327740 308353 246029 354357
5 5337 Hanadis 8 S 167158 185662 202147 135868
6 5339 NADIS 4 496648 403006 693280 657806
>
正如建议的那样,dput的结果(头部(mydata))附在下面
> dput(head(mydata))
structure(list(Quality = structure(1:6, .Label = c("rne",
"eipner", "gor", "verker 21",
"nadis 8 S", "xtra Supe",
"dis 10", "die", "almax",
"dar 1", "Supre",
"Mic", "Vik",
"TIG", "var", "ormvar",
"olmax", "imax", "imax SR"), class = "factor"), `001.2020 1. Period 2020` = c(0,
871751, 282535, 327740, 167158, 496648), `002.2020 2. Period 2020` = c(3773,
872116, 232953, 308353, 185662, 403006), `003.2020 3. Period 2020` = c(0,
790616, 368555, 246029, 202147, 693280), `004.2020 4. Period 2020` = c(0,
1086088, 218094, 354357, 135868, 657806)), idvars = "Grade", rdimnames = list(
structure(list(Grade = structure(1:47, .Label = c("rne",
"eipner", "gor", "verker 21", "nadis 8 S", "xtra Supe",
"dis 10", "die", "almax",
"dar 1", "Supre",
"Mic", "Vik",
"TIG", "var", "ormvar",
"olmax", "imax", "imax SR"), class = "factor")), row.names = c("rne",
"eipner", "gor", "verker 21",
"nadis 8 S", "xtra Supe",
"dis 10", "die", "almax",
"dar 1", "Supre",
"Mic", "Vik",
"TIG", "var", "ormvar",
"olmax", "imax", "imax SR"), class = "data.frame"), structure(list(
Period.year = structure(1:4, .Label = c("001.2020 1. Period 2020",
"002.2020 2. Period 2020", "003.2020 3. Period 2020",
"004.2020 4. Period 2020"), class = "factor")), row.names = c("001.2020 1. Period 2020",
"002.2020 2. Period 2020", "003.2020 3. Period 2020", "004.2020 4. Period 2020"
), class = "data.frame")), row.names = c(NA, 6L), class = c("cast_df",
"data.frame"))
>
这些数字应该在cast()之前清除吗?如果是,如何
如果不是,那么spread()
是否也要这样做?如果是这样,如何实现奇迹?请添加一个可复制的示例以及预期的输出。@RonakShah请查看更新的内容,我已附加了所需的格式。请使用dput(head(mydata))
提供示例数据。这让事情变得容易多了。听起来你的数据已经是长格式的了,不需要cast
或spread
。也许可以尝试库(dplyr);mydata%>%group\U by(Grade)%>%SUMMASE(收入=总和(收入))
@Brian我认为cast
是将长格式转换为宽格式;不知道cast
用于长格式…请添加一个可复制的示例以及预期输出。@Ronaksah请查看更新的内容,我已附加了所需的格式。请使用dput(head(mydata))
提供示例数据。这让事情变得容易多了。听起来你的数据已经是长格式的了,不需要cast
或spread
。也许可以尝试库(dplyr);mydata%>%group\U by(Grade)%>%SUMMASE(收入=总和(收入))
@Brian我认为cast
是将长格式转换为宽格式;不知道cast
用于长格式。。。