我想将两个变量与日期格式合并为一个 [英] I want to combine two variables into one with a date format

查看:43
本文介绍了我想将两个变量与日期格式合并为一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据集,其中有一个字符列为几个月( MONTH ),一个数字列为年份( YEAR ).为了将其用作面板数据,我需要将这些 YEAR MONTH 组合为具有日期格式的变量.

I have a data set with a character column for months (MONTH) and a numeric column indicating years (YEAR). In order to work with it as panel data, I need to unite these YEAR and MONTH into a variable with a date format.

我试图将变量 MONTH 更改为数字格式,然后将 MONTH YEAR 列合并.R不会将其识别为日期变量.

I have tried to change the variable MONTH to numeric format and then to merge MONTH with the column YEAR. R would not recognize it as a date variable.

当前看起来像这样:

  STATE          MONTH     YEAR     VALUE
California        JAN      2018      800
California        FEB      2018      780
California        MAR      2018      600
    ...           ...       ...      ...
Minesota          JAN      2018      800
Minesota          FEB      2018      780
Minesota          MAR      2018      600
    ...           ...       ...      ...

我想要这样:

  STATE          TIME        VALUE
California     01-2018        800
California     02-2018        780
California     03-2018        600
    ...           ...         ...
Minesota       01-2018        800
Minesota       02-2018        780
Minesota       03-2018        600
    ...           ...         ...

推荐答案

我建议先通过真实的R日期进行处理,使用 as.Date 生成R日期,然后使用 format 呈现所需的字符串输出.像这样:

I would recommend handling this by going through bona-fide R dates, using as.Date to generate an R date, then using format to render the string output you want. Something like this:

df$TIME <- format(as.Date(paste0(df$MONTH, df$YEAR, "01"), format="%b%Y%d"), "%m-%Y")

我将第一个数字任意分配给数据集中的每个日期,但这无关紧要,因为对 format 的调用仅包含月份和年份.

I arbitrarily assign the first to each date in your data set, but this doesn't matter, because the call to format only includes the month and year.

这篇关于我想将两个变量与日期格式合并为一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆