【发布时间】:2021-12-26 17:04:19
【问题描述】:
我正在使用同名包中的函数“seg”计算几个组与总人口的差异指数。
数据由大约 450 行组成,每行代表不同的地区,以及大约 20 列(可能被隔离的组)。这些值是居住在各个地区的各个群体的人数。这是我的 csv 文件的前几行:
Region,Germany,EU15 without Germany,Poland,Former Yugoslavia and successor countries,Former Soviet Union and successor countries,Turkey,Arabic states,West Afrika,Central Afrika,East Afrika,North America,Central America and the Carribean,South America,East and Central Asia,South and Southeast Asia - excluding Vietnam,Australia and Oceania,EU,Vietnam,Non EU Europe,Total Population
1011101,1370,372,108,35,345,91,256,18,6,3,73,36,68,272,98,3,1979,19,437,3445
1011102,117,21,6,0,0,0,6,0,0,0,7,0,6,0,7,0,156,0,3,188
1011103,2180,482,181,102,385,326,358,48,12,12,73,24,75,175,129,12,3152,34,795,5159
由于seg 函数仅适用于两列作为输入,我当前用于创建包含所有组索引的表的代码如下所示:
DI_table <- as.data.frame(0)
DI_table[1,1] <- print (seg(data =dfplrcountrygroups2019[, c( "Germany", "Total.Population")]))
DI_table[1,2] <- print (seg(data =dfplrcountrygroups2019[, c( colnames(dfplrcountrygroups2019)[3], "Total.Population")]))
DI_table[1,3] <- print (seg(data =dfplrcountrygroups2019[, c( colnames(dfplrcountrygroups2019)[4], "Total.Population")]))
DI_table[1,4] <- print (seg(data =dfplrcountrygroups2019[, c( colnames(dfplrcountrygroups2019)[5], "Total.Population")]))
# and so on...
colnames(DI_table)<- (colnames(dfplrcountrygroups2019[2:20]))
效果很好,但是每次我用我的数据更改某些内容时重新编码很麻烦,我也想将此方法用于其他数据集。
我想我可能会尝试类似下面的方法,但 seg 函数不认为它是两列的选择。
for (i in colnames(dfplrcountrygroups2019)) {
di_matrix [i] <- seg(data =dfplrcountrygroups2019[, c( "i", "Total.Population")])
}
[.data.frame(dfplrcountrygroups2019, , c("i", "Total.Population")) : 选择了未定义的列
我还想到了apply 函数,但不确定如何使其工作,因此它会重复自身,同时只是更改示例中“德国”所在的列。每次重复 seg 函数时,如何更改列的选择?
my_function <- seg(data =dfplrcountrygroups2019[, c("Germany", "Total.Population")])
apply(X = dfplrcountrygroups2019,
FUN = my_function,
MARGIN = 2
)
get(as.character(FUN), mode = "function", envir = envir) 中的错误:
找不到模式“function”的对象“my_function”
【问题讨论】:
-
发生了一些事情:
dfplrcountrygroups2019是数据框吗?似乎您正在将每个组与总人口进行比较,但此功能希望您将组与不在组中的人进行比较(例如,德国人与非德国人,而不是德国人与总人口)。?seg::seg有以下示例在一个数据框中遍历多个组的列对。这不是我会做的事情(我真的更喜欢长形和/或这样的拆分数据),但它是一个记录在案的选项。 -
非常感谢您的反馈!是的
dfplrcountrygroups是数据框。是的,我意识到我在总人口上犯了错误,现在我只是将所有其他群体与德国人进行比较,因为我没有时间为每个群体创建代表“其余人口”的新列。将研究示例!