2011-03-10 102 views
0

所以我查看了thisthis,似乎無法找到循環或迭代一個因子的一個很好的示例(或者是他們的其他/更好的方法這個?)。我有,我有一個數據幀:通過提取特定元素的因子進行迭代

> head(frame) 
    x1  x2  DateTime 
    1 100 5 2010-06-01 05:32:46 
    2 105 3 2010-06-01 05:32:23 
    3 47 20 2010-06-01 05:32:34 
    4 56 6 2010-06-01 05:33:16 
    5 98 11 2010-06-01 05:54:12 
    6 84 9 2010-06-01 05:54:05 

,我可以根據像這樣的時間打造一個因素:fact <- cut(frame$DateTime, "1 hour")從那裏,我怎麼會去提取框架$ X2的第一個和最後一個元素給出的我創造的因素? (或者就此而言,切割的第n個元素)。

會是這樣的:你想

test <- split(frame$x2, fact) 

回答

0

我不知道你所說的「解壓」的第n個元素(即你希望它在同一個對象,一個新的對象是什麼意思,做與原始對象具有相同長度的東西等)。

,因爲它的因素組操作,我會用ave。請注意,這假定您的data.frame按frame$DateTime排序。

frame <- structure(list(
    x1 = c(100L, 105L, 47L, 56L, 98L, 84L), 
    x2 = c(5L, 3L, 20L, 6L, 11L, 9L), 
    DateTime = structure(c(1275388366, 1275388343, 1275388354, 1275388396, 
    1275389652, 1275389645), class = c("POSIXct", "POSIXt"), tzone = ""), 
    fact = structure(c(1L, 1L, 1L, 1L, 1L, 1L), 
    .Label = "2010-06-01 05:00:00", class = "factor")), 
    .Names = c("x1", "x2", "DateTime", "fact"), 
    row.names = c(NA, -6L), class = "data.frame") 

transform(frame, firstx2=ave(x2, fact, FUN=function(x) x[1]), 
       lastx2 =ave(x2, fact, FUN=function(x) x[length(x)])) 

# These lines do the same as the `transform` line(s) 
frame$firstx2 <- ave(frame$x2, frame$fact, FUN=function(x) x[1]) 
frame$lastx2 <- ave(frame$x2, frame$fact, FUN=function(x) x[length(x)]) 
+0

謝謝你的幫助,如果我不清楚,我很抱歉。是的,frame $ DateTime是排序的,我想我試圖將第n個元素提取到一個對象中,然後我可以在一個覆蓋層上繪製一個類似'boxplot(frame $ x2〜fact)'的地方,看第一個或最後一個或第n個元素。 – Bob 2011-03-10 15:52:02

+0

也許我做錯了什麼,而是試圖讓這個代碼運行,我得到「在EVAL錯誤(表達式,ENVIR,enclos):對象firstx2「未找到」的錯誤。有什麼想法嗎? – Bob 2011-03-10 16:18:12

+0

@Bob:它可能是你創建'frame'的方式。我爲我的答案添加了一個「框架」示例。 – 2011-03-10 16:27:42