2017-04-10 60 views
1

我無法找到這個潛在問題的答案,因爲我真的不知道如何用幾句話來描述我想實現的目標。基本上我有2列(日出和日落)與一定數量的行。我希望將它們合併爲一列,以便組合列的第一個值取第一行第一列中的值,組合列中的第二值取第一行第二列中的值,合併列在第二行和第一列等與數據的價值,我們開始與此:r - 將特殊訂單中的2列合併爲1

df <- structure(list(sunrise = structure(c(1439635810.57809, 1439722237.7463, 
1439808664.71935, 1439895091.49609, 1439981518.07612, 1440067944.45978 
), class = c("POSIXct", "POSIXt")), sunset = structure(c(1439682771.28069, 
1439769119.75559, 1439855467.39929, 1439941814.23447, 1440028160.28404, 
1440114505.57116), class = c("POSIXct", "POSIXt"))), .Names = c("sunrise", 
"sunset"), row.names = c(NA, 6L), class = "data.frame") 

      sunrise    sunset 
1 2015-08-15 06:50:10 2015-08-15 19:52:51 
2 2015-08-16 06:50:37 2015-08-16 19:51:59 
3 2015-08-17 06:51:04 2015-08-17 19:51:07 
4 2015-08-18 06:51:31 2015-08-18 19:50:14 
5 2015-08-19 06:51:58 2015-08-19 19:49:20 
6 2015-08-20 06:52:24 2015-08-20 19:48:25 

期望得到的結果應該是這樣的:

data.frame(c("2015-08-15 06:50:10", "2015-08-15 19:52:51", "2015-08-16 06:50:37", 
"2015-08-16 19:51:59", "2015-08-17 06:51:04", "2015-08-17 19:51:07", 
"2015-08-18 06:51:31", "2015-08-18 19:50:14", "2015-08-19 06:51:58", 
"2015-08-19 19:49:20", "2015-08-20 06:52:24", "2015-08-20 19:48:25" 
)) 

    output 
1 2015-08-15 06:50:10 
2 2015-08-15 19:52:51 
3 2015-08-16 06:50:37 
4 2015-08-16 19:51:59 
5 2015-08-17 06:51:04 
6 2015-08-17 19:51:07 
7 2015-08-18 06:51:31 
8 2015-08-18 19:50:14 
9 2015-08-19 06:51:58 
10 2015-08-19 19:49:20 
11 2015-08-20 06:52:24 
12 2015-08-20 19:48:25 

我晝/夜,然後分配給每個行,並使用這些bin使用findInterval函數來日夜分類我的數據。

任何幫助,非常感謝。

編輯:謝謝你的答案,他們的工作就像一個魅力

回答

3

反覆提取行,然後轉換成向量

data.frame(output = as.POSIXct(Reduce(c, (apply(df, 1, c))))) 
#    output 
#1 2015-08-15 05:50:10 
#2 2015-08-15 18:52:51 
#3 2015-08-16 05:50:37 
#4 2015-08-16 18:51:59 
#5 2015-08-17 05:51:04 
#6 2015-08-17 18:51:07 
#7 2015-08-18 05:51:31 
#8 2015-08-18 18:50:14 
#9 2015-08-19 05:51:58 
#10 2015-08-19 18:49:20 
#11 2015-08-20 05:52:24 
#12 2015-08-20 18:48:25 

#NOTE: the values are different because of timezone 

或索引直接從data.frame

as.POSIXct(df[cbind(sort(rep(1:NROW(df), NCOL(df))), rep(1:NCOL(df), NROW(df)))]) 
2
## create a matrix of indices then order it 
o <- order(matrix(1:prod(dim(df)), nrow(df), byrow = TRUE)) 
## create the new data frame from the concatenated dates and the order vector 
data.frame(output = do.call("c", c(df, use.names = FALSE))[o]) 
#     output 
# 1 2015-08-15 03:50:10 
# 2 2015-08-15 16:52:51 
# 3 2015-08-16 03:50:37 
# 4 2015-08-16 16:51:59 
# 5 2015-08-17 03:51:04 
# 6 2015-08-17 16:51:07 
# 7 2015-08-18 03:51:31 
# 8 2015-08-18 16:50:14 
# 9 2015-08-19 03:51:58 
# 10 2015-08-19 16:49:20 
# 11 2015-08-20 03:52:24 
# 12 2015-08-20 16:48:25 
+0

*輕微變化:'減少(c,df)[矩陣(1:prod(dim(df)),nrow = ncol(df),byrow = TRUE)]' – thelatemail