只需将tapply
摘要与原始数据帧“合并”即merge
即可。
由于您没有提供示例数据,我做了一些。相应地修改。
n = 1000
id = sample(1:10, n, replace=T)
year = sample(2000:2011, n, replace=T)
destination = sample(LETTERS[1:6], n, replace=T)
`destination-year` = paste(destination, year, sep='-')
dat = data.frame(id, year, destination, `destination-year`)
现在列出您的摘要。请注意我如何重新格式化为数据框,并使名称与原始数据匹配。
incumbents = tapply(id, `destination-year`, function(x) length(unique(x)))
incumbents = data.frame(`destination-year`=names(incumbents), incumbents)
最后,合并早在与原始数据:
merge(dat, incumbents)
顺便说一句,而不是结合destination
和year
到第三个变量,像它看起来你已经做了, tapply
可以直接处理两个变量作为列表:
incumbents = melt(tapply(id, list(destination=destination, year=year), function(x) length(unique(x))))
对不起,没有示例数据...新手错误 – 2012-02-13 23:45:54