[英]What's the most efficient way to partition and access dataframe rows in R?
我需要遍歷數據框df
,其中
colnames(df) == c('year','month','a','id','dollars')
我需要遍歷所有唯一對('a','id')
,這些對是通過
counts <- count(df, c('area','normalid'))
uniquePairs <- counts[ counts$freq > 10, c('a','id') ]
接下來,我遍歷每個唯一對,找到這樣的對應行(我已對uniquePairs
每一列進行uniquePairs
適當命名):
aVec <- as.vector( uniquePairs$a )
idVec <- as.vector( uniquePairs$id )
for (i in 1:length(uniquePairs))
{
a <- aVec[i]
id <- idVec[i]
selectRows <- (df$a==a & df$id==id)
# ... get those rows and do stuff with them ...
df <- df[!selectRows,] # so lookups are slightly faster next time through
# ...
}
我知道一般不建議for循環,但是在這種情況下,我認為這是適當的。 至少在我看來,這個問題無關緊要,但也許更有效的方法可以擺脫這種循環。
數據幀中有10-100k行,並且在查找時間和nrow(df)
之間的關系要比線性關系差(盡管我尚未測試),這是nrow(df)
。
現在unique
肯定在哪里見過這些對發生的,即使它沒有保存。 有沒有一種方法可以避免這種情況,以便我有一個布爾向量可以用於每個對,以便更有效地從數據幀中選擇它們? 還是有其他更好的方法來做到這一點?
我有一種感覺,有些使用的plyr
或reshape
可以幫助我,但我仍然相對較新的很大的R生態系統,所以一些指導,將不勝感激。
data.table
是您最好的選擇:
dt = data.table(df)
dt[,{do stuff in here, then leave results in list form},by=list(a, id)]
對於某些變量的平均值的簡單情況:
dt[,list(Mean = mean(dollars)), by = list(a, id)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.