【问题标题】:Factor as date to numeric将日期因子转换为数字
【发布时间】:2013-08-10 09:53:50
【问题描述】:

很抱歉打扰这个问题,但找不到解决方案。

我有一个 data.frame 列名称日期:

 str(df$date)
 Factor w/ 360 levels "1982-11-30","1982-12-31",..: 1 4 7 10 13 16 19 22 25 28 ...

 class(a)
 [1] "factor"

我想将其转换为数值:从:“1982-11-30”到 19821130 或其他。

编辑:

最初我有这个数字格式并转换为以下因子:

date <- as.Date(as.character(df$date_num),format="%Y%m%d")

那么如何逆转呢?

【问题讨论】:

    标签: r


    【解决方案1】:

    这样的?

    dd <- structure(1:2, .Label = c("2013-01-01", "2013-02-01"), class = "factor")
    # [1] 2013-01-01 2013-02-01
    # Levels: 2013-01-01 2013-02-01
    
    as.numeric(gsub("-", "", as.character(dd), fixed=TRUE))
    # [1] 20130101 20130201
    

    【讨论】:

    • @Max,我将perl=TRUE 更改为fixed=TRUE。这应该更快(在更大的数据上)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-28
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多