簡體   English   中英

在R中,如何通過和動物園維護列名?

[英]In R, how do I maintain column names through by and zoo?

我有一個長格式的data.frame ,我想用它來構建一個寬格式的zoo系列。

data.frame看起來像:

        Date Label Value
1 2015-03-21     A     1
2 2015-03-22     B     6
3 2015-03-22     A     2
4 2015-03-23     A     7
5 2015-03-23     B     5
...

例如:

d <- data.frame(
    Date = c(Sys.Date() - 2, Sys.Date() - 1, Sys.Date() -1, Sys.Date(), Sys.Date()), 
    Label = c("A", "B", "A", "A", "B"), 
    Value = c(1, 6, 2, 7, 5))

我的結果應該是一個看起來像這樣的zoo

           A  B ...
2015-03-21 1 NA ...
2015-03-22 2  6 ...
2015-03-23 7  5 ...
...

我已成功實現此目的:

f <- function(x) {

    zoo(x$Value, order.by = x$Date)
}

do.call(merge.zoo, by(d, factor(d$Label), f))

其中ddata.frame

但是,當d只包含一個Label ,它會在某處刪除列名:

2015-03-21 2015-03-22 2015-03-23 
         1          2          7

names(d)給出NULL

即使輸出zoo是單變量的,我如何保持列名?

使用read.zoosplit=參數拆分第二列:

library(zoo)
read.zoo(d, split = 2)

贈送:

           A  B
2015-03-21 1 NA
2015-03-22 2  6
2015-03-23 7  5

問題是merge.zoo會刪除單變量zoo的名稱。

可以通過將drop = F傳遞給args列表來覆蓋此行為。 我們可以使用merge.zoo的部分函數應用程序來實現這個,當使用do.call

f <- function(x) {

    zoo(x$Value, order.by = x$Date)
}

s <- do.call(partial(merge.zoo, drop = F), by(d, factor(d$Label), f))

或沒有部分:

s <- do.call(merge.zoo, append(by(d, factor(d$Label), f), list(drop = F)))

對於d <- d[d$Label == "A", ]這給出:

           A
2015-03-21 1
2015-03-22 2
2015-03-23 7

請注意,部分功能應用需要pryr包。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM