将当月的第一个日期转换为R中的yearmon

时间:2017-09-13 00:46:44

标签: r zoo as.date as.yearqtr

我一直试图将年份作为以下示例数据集的新列。

dta<-structure(list(time = structure(c(1L, 3L, 5L, 7L, 9L, 11L, 13L, 
15L, 17L, 19L, 21L, 22L, 2L, 4L, 6L, 8L, 10L, 12L, 14L, 16L, 
18L, 20L), .Label = c("1/01/2000", "1/01/2001", "1/02/2000", 
"1/02/2001", "1/03/2000", "1/03/2001", "1/04/2000", "1/04/2001", 
"1/05/2000", "1/05/2001", "1/06/2000", "1/06/2001", "1/07/2000", 
"1/07/2001", "1/08/2000", "1/08/2001", "1/09/2000", "1/09/2001", 
"1/10/2000", "1/10/2001", "1/11/2000", "1/12/2000"), class = "factor"), 
    site = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "A", class = "factor")), .Names = c("time", 
"site"), class = "data.frame", row.names = c(NA, -22L))

可以使用以下dput访问数据集。

library(zoo)
dta$y_m = as.yearmon(as.Date(dta$time,"%m/%d/%Y"))

1] "Jan 2000" "Jan 2000" "Jan 2000" "Jan 2000" "Jan 2000" "Jan 2000" "Jan 2000"
 [8] "Jan 2000" "Jan 2000" "Jan 2000" "Jan 2000" "Jan 2000" "Jan 2001" "Jan 2001"
[15] "Jan 2001" "Jan 2001" "Jan 2001" "Jan 2001" "Jan 2001" "Jan 2001" "Jan 2001"
[22] "Jan 2001"

我尝试使用以下代码并返回所有12个月的同一个月。

 .grouped-link {
    cursor: pointer;
}

.slideout-link {
    span.show:hover {
        color: $darkgrey;
    }
}
.section-subtitle a, a.section-subtitle {
    color: $darkgrey;
    float: right;
    text-transform: uppercase;
    font-size: 16px;
    font-weight: 400;
    letter-spacing: 2px;
    margin-top: 65px;
    text-decoration: none;
    border-bottom: 1px solid $darkgrey;

        &:hover {
        border-color: $midgrey;
        color: $midgrey;
        text-decoration: none;
    }
}

.underline-link {
    border-bottom: 1px solid $lightgrey;
    cursor: pointer;
    padding-bottom: 5px;
    text-transform: uppercase;
    width: 150px;

    &.dark {
        border-color: $grey;
        color: $grey;
    }

    &:hover {
        border-color: $midgrey;
        color: $midgrey;
        text-decoration: none;
    }

    &.light {
        border-color: $upmidgrey;
        color: $upmidgrey;
    }

    &.lightest {
        color: $lightgrey;
    }
}

.inline-link {
    color: $grey;
    cursor: text;

    &:hover {
        text-decoration: none;
        cursor: text;
    }
}

a[target="_blank"]:not(.inline-link):hover {
    text-decoration: none;
    cursor: pointer;
}

任何人都可以帮助我,让它正确。谢谢

1 个答案:

答案 0 :(得分:4)

试试这个:

require(zoo)
as.yearmon(dta$time, format="%d/%m/%Y")

输出:

 [1] "Jan 2000" "Feb 2000" "Mar 2000" "Apr 2000" "May 2000" "Jun 2000"
 [7] "Jul 2000" "Aug 2000" "Sep 2000" "Oct 2000" "Nov 2000" "Dec 2000"
[13] "Jan 2001" "Feb 2001" "Mar 2001" "Apr 2001" "May 2001" "Jun 2001"
[19] "Jul 2001" "Aug 2001" "Sep 2001" "Oct 2001"