gpt4 book ai didi

在 R 中重建数据

转载 作者:行者123 更新时间:2023-12-02 01:58:39 25 4
gpt4 key购买 nike

现在我有这样一个数据集:

  country index     value
1 AUS GPD 0.8004142
2 AUS GNI 0.8251010
3 AUS CPI 0.6675700
4 HUN GPD 0.3520509
5 HUN GNI 0.4821505
6 HUN CPI 0.3623341
7 USA GPD 0.6431452
8 USA GNI 0.9119910
9 USA CPI 0.6616684

然后我使用 subset 和 merge 命令重建数据如下

gdp<-subset(x,index=="GDP")# subset by index
> gdp
country index value
1 AUS GDP 0.8004142
4 HUN GDP 0.3520509
7 USA GDP 0.6431452
names(gdp)[3]<-"GDP" # rename 'value' to 'GDP'
gdp<-gdp[c(-2)]
gni<-subset(x,index=="GNI")
names(gni)[3]<-"GNI"
gni<-gni[c(-2)]
cpi<-subset(x,index=="CPI")
names(cpi)[3]<-"CPI"
cpi<-cpi[c(-2)]
total<-merge(gdp, gni, by="country")
total1<-merge(total, cpi, by="country")
> total1
country GDP GNI CPI
1 AUS 0.8004142 0.8251010 0.6675700
2 HUN 0.3520509 0.4821505 0.3623341
3 USA 0.6431452 0.9119910 0.6616684

我正在寻找一种像这样重建数据的简单方法。请提供一些建议(示例代码)。非常感谢任何帮助。

最佳答案

这是一个非常基本的“ reshape ”问题。

最直接的方法是使用“reshape2”中的dcast:

> library(reshape2)
> dcast(mydf, country ~ index)
country CPI GNI GPD
1 AUS 0.6675700 0.8251010 0.8004142
2 HUN 0.3623341 0.4821505 0.3520509
3 USA 0.6616684 0.9119910 0.6431452

或者,在基础 R 中,有 xtabsxtabs 输出一个 matrix,因此使用 as.data.frame.matrix 来获取您的 data.frame .

> as.data.frame.matrix(xtabs(value ~ country + index, mydf))
CPI GNI GPD
AUS 0.6675700 0.8251010 0.8004142
HUN 0.3623341 0.4821505 0.3520509
USA 0.6616684 0.9119910 0.6431452

关于在 R 中重建数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18532357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com