【问题标题】:How to extract only year from the date in dataframes? [duplicate]如何从数据框中的日期中仅提取年份? [复制]
【发布时间】:2015-10-23 12:11:20
【问题描述】:

这是我的数据...& 我只需要使用基本的 R 来提取数据(不要使用 mysql、php、python、c# 或任何其他)

**service**        **Date**
disconnected        2013-01-14
disconnected        2013-03-15
disconnected        2012-02-24
disconnected        2012-12-05
disconnected        2012-06-08
disconnected        2011-05-08 
disconnected        2010-10-11 
disconnected        2010-12-02

我需要提取的数据只有一年......从日期......&稍后我需要再次将其分配给新变量或向量......

下面的输出应该是....

OUTPUT
**service**        **Date**
disconnected        2013
disconnected        2013
disconnected        2012
disconnected        2012
disconnected        2012
disconnected        2011 
disconnected        2010 
disconnected        2010

【问题讨论】:

    标签: r


    【解决方案1】:

    有很多选择。一种方法是使用 substr 从 'Date' 列中获取前 4 个字符元素(假设我们不会返回 > 1000 )

     df1$Year <- substr(df1$Date, 1,4)
    

    或者我们匹配从-开始的子字符串,后跟一个或多个字符到字符串的末尾,用''替换sub

    df1$Year <- sub('-.*$', '', df1$Date)
    

    或者我们可以通过转换为POSIXlt 类来提取year

     strptime(df1$Date, '%Y-%m-%d')$year+1900
    

    如果我们被允许使用包,library(lubridate) 有一个方便的功能,即year

    library(lubridate)
    year(df1$Date)
    

    数据

    df1 <- structure(list(service = c("disconnected", "disconnected", "disconnected", 
    "disconnected", "disconnected", "disconnected", "disconnected", 
    "disconnected"), Date = c("2013-01-14", "2013-03-15", "2012-02-24", 
    "2012-12-05", "2012-06-08", "2011-05-08", "2010-10-11", "2010-12-02"
    )), .Names = c("service", "Date"), class = "data.frame",
    row.names = c(NA, -8L))
    

    【讨论】:

    • thnq u :) strptime 命令有效....我给出了该数据,例如实际上我有大量数据...lyk 有 309 条记录,所以我无法指定这么多日期... .Date=c("...")...我如何将修改后的数据分配给新变量,例如:Z& dat Z 应该只包含服务列和修改日期即年份。
    • @arshia 在使用read.table 读取文件后,我使用dput 来获得帖子中所示的结构。在你的情况下,如果我理解你的评论,你只需要df1 &lt;- read.table('yourfile.txt', header=TRUE, stringsAsFactors=FALSE)
    • 是的,我明白了很多:)
    • Year:num[1:554] 2013 2013 2013.....2012 2012.... "Year" 是值 & 需要将其添加到我的数据框 "mydata" & mydata 包括554 条记录......“服务”和“日期”我从日期开始删除年份并希望将其添加到现有数据框......
    • 谢谢。它有效
    【解决方案2】:

    如果您将date 设为日期变量,format 可以很容易地提取年份。

    D <- data.frame(service = rep("disconnected", 3),
                    date = c("2013-01-14", "2013-03-15", "2012-02-24"))
    
    D$year <- format(as.Date(D$date), format = "%Y")
    
    D
    
           service       date year
    1 disconnected 2013-01-14 2013
    2 disconnected 2013-03-15 2013
    3 disconnected 2012-02-24 2012
    

    【讨论】:

    • thnq u :) 我给了那个数据,例如实际上我有大量数据...lyk 有 309 条记录,所以我不能指定这么多日期....Date=c(".. .")...我如何将修改后的数据分配给新变量,例如:Z& dat Z 应仅包含服务列和修改日期即年份。
    • 我有 554 条记录,我无法在以下命令中指定日期:date = c("2013-01-14", "2013-03-15", "2012-02 -24")) ...如何加载554条记录的日期.....??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    • 2012-09-08
    • 2018-10-05
    相关资源
    最近更新 更多