我有双边交流数据,例如:
library(datatable)
mwe <- data.table(Importer=c("Country_A","Country_A","Country_A","Country_A",
"Country_B","Country_B","Country_B","Country_B",
"World","World","World","World",
"Country_C","Country_C","Country_C","Country_C"),
Short_Importer=c("A","A","A","A",
"B","B","B","B",
"W","W","W","W",
"C","C","C","C"),
Exporter=c("Country_A", "Country_B", "World", "Country_C",
"Country_A", "Country_B", "World", "Country_C",
"Country_A", "Country_B", "World", "Country_C",
"Country_A", "Country_B", "World", "Country_C"),
Value=c(0,12,36,24,
10,0,44,34,
30,22,110,58,
20,10,30,0))
我已将其更改为更广泛的格式
mwe_wide <- dcast(mwe, Importer + Short_Importer ~ Exporter, value.var = "Value")
我想要这个数据,但是在列中使用份额而不是值。因此,我想简单地用相同的值除以行世界的同一列上的数量来替换第3至5列。我认为这不是很复杂,但是还没有找到令人满意的方法。实际上,我有几个分区,所以我要避免删除线世界,然后按总和除法。
desired_output <- data.table(Importer=c("Country_A", "Country_B", "Country_C", "World"),
Short_Importer=c("A","B","C","W"),
Country_A =c(0,0.33,0.66,1),
Country_B =c(0,0.55,0.45,1),
Country_C =c(0,0.41,0.59,1),
World =c(0.33,0.40,0.27,1))
如果我们需要除以“进口商”为“世界”的最后一行,请>
mwe_wide[, (3:6) := lapply(.SD, function(x) round(x/x[Importer == "World"], 2)), .SDcols = 3:6] mwe_wide # Importer Short_Importer Country_A Country_B Country_C World #1: Country_A A 0.00 0.55 0.41 0.33 #2: Country_B B 0.33 0.00 0.59 0.40 #3: Country_C C 0.67 0.45 0.00 0.27 #4: World W 1.00 1.00 1.00 1.00
或带有
Map
mwe_wide[, (3:6) := Map(`/`, .SD, .SD[Importer == 'World']), .SDcols = 3:6]