对于示例数据框:
migration <- structure(list(area.old = structure(c(2L, 2L, 2L, 2L, 2L, 2L,
2L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 1L,
3L, NA, NA, NA), .Label = c("leeds", "london", "plymouth"), class = "factor"),
area.new = structure(c(7L, 13L, 3L, 2L, 4L, 7L, 6L, 7L, 6L,
13L, 5L, 8L, 7L, 11L, 12L, 9L, 1L, 10L, 11L, NA, NA, NA,
NA, 7L, 6L, 6L), .Label = c("bath", "bristol", "cambridge",
"glasgow", "harrogate", "leeds", "london", "manchester",
"newcastle", "oxford", "plymouth", "poole", "york"), class = "factor"),
persons = c(6L, 3L, 2L, 5L, 6L, 7L, 8L, 4L, 5L, 6L, 3L, 4L,
1L, 1L, 2L, 3L, 4L, 9L, 4L, 5L, 7L, 9L, 10L, 15L, 4L, 7L)), .Names = c("area.old",
"area.new", "persons"), class = c("data.table", "data.frame"), row.names = c(NA,
-26L), .internal.selfref = <pointer: 0x0000000000220788>)
我希望使用以下代码将数据汇总到几个数据框中:
moved.from <- migration[as.character(area.old)!=as.character(area.new),
.(persons = sum(persons)),
by=.(moved.from = area.old)]
moved.to <- migration[as.character(area.old)!=as.character(area.new),
.(persons = sum(persons)),
by=.(moved.to = area.new)]
这会生成两个汇总表,首先详细说明已经从&area; old.old&#39;区域移动的人员总数。第二个表格列出了人们搬到的目的地(在&#39; area.new&#39;)。这里建议使用此代码(Producing smmary tables for very large datasets)。
当我在我自己的数据上尝试时出现了一个问题,因为我没有告诉R如何处理区域内的NAs。&#39;或者&#39; area.new&#39;列。如何修改此代码以添加所有NA(即将它们包含在moving.from和moving.to数据框底部的行中,添加了NA中的总人数)?
对此的任何帮助都将非常感激。
答案 0 :(得分:1)
只需在每个过滤器中添加| is.na
作为附加条件
migration[as.character(area.old) !=
as.character(area.new) |
is.na(area.old),
.(persons = sum(persons)),
by = .(moved.from = area.old)]
# moved.from persons
# 1: london 24
# 2: leeds 17
# 3: plymouth 19
# 4: NA 26
和
migration[as.character(area.old) !=
as.character(area.new) |
is.na(area.new),
.(persons = sum(persons)),
by = .(moved.to = area.new)]
# moved.to persons
# 1: york 9
# 2: cambridge 2
# 3: bristol 5
# 4: glasgow 6
# 5: leeds 8
# 6: london 5
# 7: harrogate 3
# 8: manchester 4
# 9: poole 2
# 10: newcastle 3
# 11: bath 4
# 12: oxford 9
# 13: NA 31
作为旁注,我建议将两列转换为字符类,并避免在每个操作中调用as.character
。以下应该做
migration[, names(migration)[-3L] := lapply(.SD, as.character), .SDcols = -"persons"]
现在,您可以在不调用area.old
的情况下比较area.new
和as.character