如何根据特定数据行更改数据表中的列

How to change columns in a datable based on a specific line of data

我有双边交流数据,如:

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))

如果我们需要除以 'Importer' 为 'World'

的最后一行
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]