0

我有一个数据框,其中包含公司在不同年份对不同国家的年度出口。我的问题是我需要创建一个变量,表示每年每个国家有多少家公司。我可以用“tapply”命令完美地做到这一点,比如

incumbents <- tapply(id, destination-year, function(x) length(unique(x)))

它工作得很好。我的问题是现任者有长度length(destination-year),我需要它有长度length(id)——每年有很多公司为每个目的地提供服务——以便在随后的回归中使用它(当然,以与年份和目的地相匹配的方式)。“for”循环可以做到这一点,但由于数据库非常庞大,因此非常耗时。

有什么建议么?

4

3 回答 3

1

只需将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)

顺便说一句,不像您已经完成的那样将destinationand组合year成第三个变量,tapply可以直接将两个变量作为列表处理:

incumbents = melt(tapply(id, list(destination=destination, year=year), function(x) length(unique(x))))
于 2012-02-13T20:30:12.453 回答
1

您没有提供可重现的示例,因此我无法对此进行测试,但您应该可以使用ave

incumbents <- ave(id, destination-year, FUN=function(x) length(unique(x)))
于 2012-02-13T21:11:05.703 回答
0

使用@JohnColby 的优秀示例数据,我想到了更多类似的东西:

#I prefer not to deal with the pesky '-' in a variable name
destinationYear = paste(destination, year, sep='-')

dat = data.frame(id, year, destination, destinationYear)

#require(plyr)
dat <- ddply(dat,.(destinationYear),transform,newCol = length(unique(id)))

#Or if more speed is required, use data.table
require(data.table)
datTable <- data.table(dat)

datTable <- datTable[,transform(.SD,newCol = length(unique(id))),by = destinationYear]
于 2012-02-13T21:06:00.033 回答