【发布时间】:2014-06-24 19:07:54
【问题描述】:
我有一个看起来像这样的 data.frame
dput(repex) = structure(list(cat = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L), .Label = c("x",
"y", "z"), class = "factor"), year = c(1980, 1980, 1982, 1982,
1990, 1991, 1991, 1991, 1993, 1981, 1981, 1983, 1990, 1996, 1996,
1996, 1996, 1999, 2002, 1994), org = structure(c(2L, 3L, 4L,
2L, 5L, 6L, 7L, 8L, 9L, 2L, 3L, 5L, 3L, 10L, 11L, 4L, 9L, 10L,
3L, 9L), .Label = c("709340", "a", "b", "c", "d", "f", "j", "k",
"e", "h", "m"), class = "factor")), .Names = c("cat", "year",
"org"), row.names = c(NA, 20L), class = "data.frame")
我想创建一个新对象(最好是 data.table 或 data.frame),其中 org 的元素水平分组在特定的 cat, year 组合后面
我尝试运行以下命令:
repex <- data.table(repex)
setkey(repex,cat,year)
repex[, list(org), by="cat,year"] #OR
repex[, paste(org,sep="_"), by="cat,year"] # OR
with(repex, tapply(org,paste(cat,year,sep="_"),paste))
前两个 data.table 选项仅复制整个 data.table 和 tapply 选项(应用于 repex 作为 data.table 或 data.frame)适用于小型数据集,但创建一个不太方便的列表对象因为我需要将输出添加到另一个基于 cat_year 组合的 data.frame... 此外,对于一个长数据集(nrow > 100,000),它需要永远,特别是在某些情况下它需要粘贴 > 100 org-变种。
我想要的输出是一个看起来像这样的 data.table
x 1980 a b
x 1982 a c # org would ideally be rearranged
x 1990 d
x 1991 f j k
...
y 1996 c e h m
...
z 2002 b
【问题讨论】:
标签: r dataframe aggregate data.table apply