2013-03-18 19 views
0

我正在處理一個大型數據集,我想查找所有站點通用的日期。查找日期對於數據框中的所有站點通用

site <- c(1,1,1,2,2,2,2,3,3,4,4,4) 
date <- c("4th Nov","5th Nov","6th Nov","5th Nov","6th Nov","7th Nov","8th Nov","5th Nov","6th Nov","6th Nov","7th Nov","8th Nov") 
temperature <- c(3,5,7,3,6,8,5,3,5,7,8,9) 
data <- data.frame(site,date,temperature) 

common.dates(data) 
[1] "6th Nov" 

任何幫助,將不勝感激。謝謝!

+1

請定義「所有網站通用」。 – 2013-03-18 15:42:28

+0

這個資料中的所有地點沒有共同的日期! – 2013-03-18 15:44:11

+0

感謝您的注意。 – Brian 2013-03-18 15:47:37

回答

1

你可以做到這一點(即使它不是最優化):

dates <- union(NULL,data$date) 
sites <- union(data$site,NULL) 

w <- array(0,length(dates)) # number sites per date 
for (i in sites) 
    for (j in 1:length(dates)) 
     w[j] <- w[j] + dates[j] %in% data$date[data$site==i] 

dates[w == length(sites)] # returns the dates common to all sites 
+0

這其中實際上效果更好! – Brian 2013-03-19 11:29:08

+0

你的意思是說速度更快? – Pop 2013-03-19 11:37:21

+0

我的意思是'減少(相交,拆分(數據$日期,數據$站點))''不會在我的「真實」數據框架上工作,我不知道爲什麼......但你的方法會。由於這是一個與工作有關的問題,我不確定是否值得我馬上排除故障。也許以後,但我只想說這種方法比其他方法更靈活。 – Brian 2013-03-19 12:20:36

2

一個使用plyr方式:

with(ddply(data, .(date), function(x) all(1:4 %in% x$site)), date[V1 == TRUE]) 
# [1] 6th Nov 
6

它的工作原理與splitintersect組合,和Reduce

Reduce(intersect, split(data$date, data$site)) 

[1] "6th Nov" 
+0

@Arun最後你得到了你的'Reduce'的例子... – 2013-03-18 16:19:02

+0

是的,但如果我是一個想出這種華麗的解決方案的人,會讓我更開心! :) – Arun 2013-03-18 16:19:44