[英]How do I combine two vectors of different length in R
我定期進行一組測量,但有些測量結果丟失了:
measurement_date value
1 2011-01-17 13:00:00 5
2 2011-01-17 13:04:00 5
3 2011-01-17 13:08:00 7
4 2011-01-17 13:12:00 8
5 2011-01-17 13:16:00 4
6 2011-01-17 13:24:00 6
7 2011-01-17 13:28:00 5
8 2011-01-17 13:32:00 6
9 2011-01-17 13:36:00 9
10 2011-01-17 13:40:00 8
11 2011-01-17 13:44:00 6
12 2011-01-17 13:48:00 6
13 2011-01-17 13:52:00 4
14 2011-01-17 13:56:00 6
我有一個函數,它將處理值並可以處理缺失值,但行必須在那里,所以我生成一個每分鍾有一行的數組,如下所示:
times <- timeSequence(from=.., length=60, by="min")
現在我每小時都有一行,但我需要合並數據。 我試過這樣的事情,但不能完全正確:
lapply(times, function(time) {
n <- as.numeric(time)
v <- Position(function(candidate) {
y <- as.numeric(candiated)
n == y
}
.. insert the value into the row here ..
}
但我只是得到錯誤和警告。 我是否以正確的方式解決問題? 我真的想要一個具有每分鍾值的“完整”數組,因為將有許多不同的函數將運行讀數,如果它們可以假設它就在那里,它就更容易實現它們。
DF <- data.frame(measurement_date = seq(as.POSIXct("2011-01-17 13:00:00"),
as.POSIXct("2011-01-17 13:56:00"),
by = "mins")[seq(1, 57, by = 4)][-6],
value = c(5,5,7,8,4,6,5,6,9,8,6,6,4,6))
full <- data.frame(measurement_date = seq(as.POSIXct("2011-01-17 13:00:00"),
by = "mins", length = 60),
value = rep(NA, 60))
可以使用兩種方法,第一種是merge
:
> v1 <- merge(full, DF, by.x = 1, by.y = 1, all = TRUE)[, c(1,3)]
> names(v1)[2] <- "value" ## I only reset this to pass all.equal later
> head(v1)
measurement_date value
1 2011-01-17 13:00:00 5
2 2011-01-17 13:01:00 NA
3 2011-01-17 13:02:00 NA
4 2011-01-17 13:03:00 NA
5 2011-01-17 13:04:00 5
6 2011-01-17 13:05:00 NA
第二個是通過使用%in%
派生的指標變量:
> want <- full$measurement_date %in% DF$measurement_date
> full[want, "value"] <- DF[, "value"]
> head(full)
measurement_date value
1 2011-01-17 13:00:00 5
2 2011-01-17 13:01:00 NA
3 2011-01-17 13:02:00 NA
4 2011-01-17 13:03:00 NA
5 2011-01-17 13:04:00 5
6 2011-01-17 13:05:00 NA
> all.equal(v1, full)
[1] TRUE
合並版本是強烈的首選,但需要一點點的工作。 %in%
解決方案僅適用於此處,因為數據在DF
和full
中都按時間順序排列,因此我之前的“首選”。 然而,很容易按時間順序獲得/確保這兩個對象,因此這兩種方法都需要一些精細的工作。 我們可以修改%in%
方法以按順序獲取兩個變量(重新開始full
):
full2 <- data.frame(measurement_date = seq(as.POSIXct("2011-01-17 13:00:00"),
by = "mins", length = 60),
value = rep(NA, 60))
full2 <- full2[order(full2[,1]), ] ## get full2 in order
DF2 <- DF[order(DF[,1]), ] ## get DF in order
want <- full$measurement_date %in% DF$measurement_date
full2[want, "value"] <- DF2[, "value"]
> all.equal(full, full2)
[1] TRUE
> all.equal(full2, v1)
[1] TRUE
>
在你的函數中,as.numeric(candiated)應該是as.numeric(候選者)。 還有一個支架丟失。 我不知道你在你的功能中究竟想要實現什么,但它對我來說看起來非常復雜。
嘗試
merge(Data,times,by.x=1,by.y=1,all.y=T)
這應該給你一些工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.