lapply中的rbind无法理解日期格式

时间:2014-07-24 17:14:50

标签: r date format lapply rbind

我有以下代码:

    tradingDates <- c(as.Date("1996-12-31", format = "%Y-%m-%d" ), 
                      as.Date("1997-12-31", format = "%Y-%m-%d" ))
    d1 <- data.frame(CUSIP=c("039229109","M33228109"),
             Port.Weights=as.numeric(c("3.571429","4.976429")), 
             Trade.Date = as.Date("1996-12-31", format = "%Y-%m-%d" ), stringsAsFactors = FALSE)
    d2 <- data.frame(CUSIP=c("432764733","324K32586"),
             Port.Weights=as.numeric(c("6.243803","1.469823")), 
             Trade.Date = as.Date("1997-12-31", format = "%Y-%m-%d" ), stringsAsFactors = FALSE)
    myList <- list(d1, d2)

    thePorts <- lapply(seq_along(myList), function(x)
                       rbind(myList[[x]],
                             c("78462F10", 
                               sum(as.numeric((-.01)*myList[[x]]$Port.Weights[1])), 
                               as.Date(as.character(tradingDates[x]), format= "%Y-%m-%d")),
                             c("CASH_USD",
                               sum(as.numeric((.01)*myList[[x]]$Port.Weights[1])),
                               as.Date(as.character(tradingDates[x]), format= "%Y-%m-%d"))))

我得到的错误是:

     Error in charToDate(x) : character string is not in a standard unambiguous format 

我已经尝试了我能想到的每种方法来格式化这个日期,应该注意到在rbind和lapply之外,这行很好用:

    x=5
    format(as.Date(as.character(tradeDates[x]), format= "%Y-%m-%d"), "%Y%m%d")

1 个答案:

答案 0 :(得分:1)

问题在于您使用c()混合数据。类型。 c()仅用于组合相同类型的元素(除非由包重载),因此它会将所有内容强制转换为相同的data.type。如果你运行

lapply(seq_along(myList), function(x)
    c("78462F10", 
    sum(as.numeric((-.01)*myList[[x]]$Port.Weights[1])), 
    as.Date(as.character(tradingDates[x]), format= "%Y-%m-%d")))

# [[1]]
# [1] "78462F10"    "-0.03571429" "9861"       
# 
# [[2]]
# [1] "78462F10"    "-0.06243803" "10226"  

您会看到所有内容都转换为字符串。这包括首次转换为数字的日期,此处由1970年1月1日以来的天数表示。虽然简单向量只能保存一种类型的数据,但list()能够保存不同的数据类型。所以将代码更改为

thePorts <- lapply(seq_along(myList), function(x)
    rbind(myList[[x]],
        list("78462F10", 
            sum(as.numeric((-.01)*myList[[x]]$Port.Weights[1])), 
            as.Date(as.character(tradingDates[x]), format= "%Y-%m-%d")),
        list("CASH_USD",
            sum(as.numeric((.01)*myList[[x]]$Port.Weights[1])),
            as.Date(as.character(tradingDates[x]), format= "%Y-%m-%d"))
    )
)

返回

[[1]]
      CUSIP Port.Weights Trade.Date
1 039229109   3.57142900 1996-12-31
2 M33228109   4.97642900 1996-12-31
3  78462F10  -0.03571429 1996-12-31
4  CASH_USD   0.03571429 1996-12-31

[[2]]
      CUSIP Port.Weights Trade.Date
1 432764733   6.24380300 1997-12-31
2 324K32586   1.46982300 1997-12-31
3  78462F10  -0.06243803 1997-12-31
4  CASH_USD   0.06243803 1997-12-31

根据需要(我假设)