r - 从数据框列表中提取并组合具有相同名称的列
问题描述
我得到了 17 个数据框的列表,其中包含多个国家的多个宏观经济变量,数据框的结构如下:
df$CPI
Date US Argentina Vietnam India Indonesia Philippines
1564531200 1.8 54.4 2.4 3.1 3.3 2.4
1561852800 1.6 55.8 2.2 3.2 3.3 2.7
1559260800 1.8 57.3 2.9 3.0 3.3 3.2
df$CapitalAccount
Date US Argentina Brazil China Turkey Thai
2019-06-30 0 13.8 49.0 -58.5 -7.2 27.9
2019-03-31 0 32.2 98.1 -26.3 21.4 0.0
2018-12-31 2721 16.2 59.8 -213.1 0.5 0.0
2018-06-30 -5 10.9 82.0 -50.6 -2.7 0.0
我正在尝试按国家/地区名称重新组织这些数据框,例如:
US
Date CPI CapitalAccount .......(the other 14 macro variables)
2019-06-30
2019-03-31
2018-12-31
Argentina
Date CPI CapitalAccount .......(the other 14 macro variables)
2019-06-30
2019-03-31
2018-12-31
.
.
.
.
我尝试使用 for 循环遍历数据帧列表中的每个数据帧,并通过该数据帧的 colnames() 获取列,但它不起作用,结果给了我许多重复的 NA 和日期。
For US:
for (i in 1:length(df)){
NewUS <- df[[i]][,which(colnames(df[[i]])=='US')]
US <- merge(US, NewUS)
i <- i+1
}
US
For Argentina:
for (i in 1:length(df)){
NewArgentina <- df[[i]][,which(colnames(df[[i]])=='Argentina')]
Argentina <- merge(Argentina, NewArgentina)
i <- i+1
}
Argentina
解决方案
编辑:根据@Gregor 的建议。我使用idcol
andfill = T
来替换 for 循环。希望这可以帮助。在下面的代码中,df1
和df2
是虚拟数据表。在您的情况下,它们将是 CPI、CapitalAccount... 首先,我们从每个表中选择列,在列表中的每个数据表中添加一个新列,type
并在列中分配经济变量。接下来,我们现在使用rbindlist()
绑定列表,因为您的数据表具有确切的列。
library(data.table)
df1 <- data.table(date = rep(seq(from = as.Date('2019-01-01'), to = as.Date('2019-01-05'), by = 'day'), 5),
US = runif(25),
Argentina = runif(25),
Thailand = runif(25),
China = runif(25))
df2 <- data.table(date = rep(seq(from = as.Date('2019-01-01'), to = as.Date('2019-01-05'), by = 'day'), 5),
US = runif(25),
Argentina = runif(25),
Japan = runif(25))
l1 <- list(df1, df2)
names(l1) <- c('GDP', 'CPI')
x <- rbindlist(l1, idcol = 'type', fill = TRUE) # this works even when the columns are different for each table
现在我们将所有数据表组合在一起,我们可以重塑表以使其看起来像您想要的结果。
x1 <- melt(x, id.vars = c('date', 'type'), measure.vars = c('US', 'Argentina'), variable.name = 'country', value.name = 'value')
dcast(x1, date + country ~ type, value.var = 'value')
推荐阅读
- machine-learning - 不同的随机权重初始化导致不同的性能
- javascript - 如何在对象的给定键处遍历数组?
- python - 如何将一堆默认值添加到 python/django 日志记录
- sql - 将 SQL 行标题转置到第一列
- android - buildToolsVersion 28.0.3 - 检索项目的父项时出错:找不到与给定名称匹配的资源
- regex - Bash 将正则表达式值添加到数组
- java - Java调用包含序列的MSSQL查询获取无效对象
- ios - Swift:从不同的目标调用函数
- hive - 如何在 Hive 中正确进行条件聚合
- python - Flask+nginx+uwsgi:如果flask没有路由,则仅使用nginx提供url