我是一名有用的助手,可以为您进行翻译。以下是需要翻译的内容:
我有一个在R中从数据库获取的data.table,看起来像这样:
date,identifier,description,location,value1,value2
2014-03-01,1,foo,1,100,200
2014-03-01,1,foo,2,200,300
2014-04-01,1,foo,1,100,200
2014-04-01,1,foo,2,100,200
2014-05-01,1,foo,1,100,200
2014-05-01,1,foo,2,100,200
2014-03-01,2,bar,1,100,200
2014-04-01,2,bar,1,100,200
2014-05-01,2,bar,1,100,200
2014-03-01,3,baz,1,100,200
2014-03-01,3,baz,2,200,300
2014-04-01,3,baz,1,100,200
2014-04-01,3,baz,2,100,200
2014-05-01,3,baz,1,100,200
2014-05-01,3,baz,2,100,200
2014-05-01,4,quux,2,100,200
<SNIP>
为了对数据进行一些计算,我希望将每个日期、标识符、描述和位置的组合都转换成表格中的一行,并将value1和value2的值设为NA。我知道日期的范围以及位置可能的所有取值。
我对R和data.table都不熟悉,目前感到很困惑。对于以上示例表格,我希望得到的结果是:
date,identifier,description,location,value1,value2
2014-03-01,1,foo,1,100,200
2014-03-01,1,foo,2,200,300
2014-04-01,1,foo,1,100,200
2014-04-01,1,foo,2,100,200
2014-05-01,1,foo,1,100,200
2014-05-01,1,foo,2,100,200
2014-03-01,2,bar,1,100,200
2014-03-01,2,bar,2,NA,NA
2014-04-01,2,bar,1,100,200
2014-04-01,2,bar,2,NA,NA
2014-05-01,2,bar,1,100,200
2014-05-01,2,bar,2,NA,NA
2014-03-01,3,baz,1,100,200
2014-03-01,3,baz,2,200,300
2014-04-01,3,baz,1,100,200
2014-04-01,3,baz,2,100,200
2014-05-01,3,baz,1,100,200
2014-05-01,3,baz,2,100,200
2014-03-01,4,quux,1,NA,NA
2014-03-01,4,quux,2,NA,NA
2014-04-01,4,quux,1,NA,NA
2014-04-01,4,quux,2,NA,NA
2014-05-01,4,quux,1,NA,NA
2014-05-01,4,quux,2,100,200
数据库中的数据是稀疏的,因为对于每个日期,一个给定的标识符/描述/位置组合可能有任意数量的条目或根本没有。我想要在给定日期范围内(例如2014年3月1日到2014年5月1日),每个标识符/描述和位置在表中都有一行。
这似乎是一个有趣的 data.table 技巧,但我无从下手。
编辑: 对于一个标识符/描述,我曾经在较小的规模上通过合并另一个数据表来完成此操作,但我不确定如何处理多个标识符/描述和位置的复杂性。
非常感谢您的回复。
以下是可以轻松复制到 R 中的原始数据的 dput 输出:
structure(list(date = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 1L, 2L, 3L, 1L, 1L, 2L, 2L, 3L, 3L, 3L),
.Label = c("2014-03-01", "2014-04-01", "2014-05-01"), class = "factor"),
identifier = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 4L),
description = structure(c(3L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 4L),
.Label = c("bar", "baz", "foo", "quux"), class = "factor"),
location = c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 2L),
value1 = c(100L, 200L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 200L, 100L, 100L, 100L, 100L, 100L),
value2 = c(200L, 300L, 200L, 200L, 200L, 200L, 200L, 200L, 200L, 200L, 300L, 200L, 200L, 200L, 200L, 200L)),
.Names = c("date", "identifier", "description", "location", "value1", "value2"),
row.names = c(NA, -16L),
class = c("data.table", "data.frame"))
rbind(DT0,DT0[,.(value1=NA_integer_,value2=NA_integer_),by=.(date,identifier,description,location)])
符合您的口头描述,但您给出的输出只更改了bar
行。 - FrankCJ
设置键(key),尽管文档描述的非常奇怪。 (文档没有明确说明其已设置键,而是说该对象获得了“排序”[对应于具有键的对象属性]。) - Frank