2012-02-13 5 views
0

私は、異なる年に異なる国に企業を年間輸出するデータフレームを持っています。私の問題は、毎年、各国にいくつの企業があるかという変数を作成する必要があるということです。タフな結果を元のデータフレームに復元するR

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

のように、「tapply」コマンドでこれを完全に行うことができます。私の問題は、現職者は長さがlength(destination-year)であり、長さがあることが必要ですlength(id) - 毎年多くの企業がそれぞれの目的地にサービスを提供しているので、それは後続の回帰で使用します(もちろん、年と目的地に一致する方法で)。 "for"ループはこれを行うことができますが、データベースが非常に巨大であるため、非常に時間がかかります。

提案がありますか?

+0

例のデータがありません。初心者のミス –

答えて

1

あなたが再現可能な例を提供していないので、私はこれをテストすることはできませんが、次のことができるようにすべきですave

incumbents <- ave(id, destination-year, FUN=function(x) length(unique(x))) 
+0

素晴らしいです。ありがとう!! –

1

mergeの元のデータフレームをそのままtapplyサマリーにマージしてください。

サンプルデータを提供していないので、いくつか作成しました。それに応じて変更します。

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) 

を、代わりに第三変数にdestinationyearを組み合わせることで、あなたがやったと思われるように、 tapplyは、両方の変数をリストとして直接扱うことができます。

incumbents = melt(tapply(id, list(destination=destination, year=year), function(x) length(unique(x)))) 
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] 
関連する問題