简体   繁体   English

如何将数据帧拆分为奇数和偶数年?

[英]How can I split a dataframe into odd and even years?

I have a dataframe of this format: 我有这种格式的数据框:

    19620101    1   2   4
    19630102    6   2   3
    19640103    0   2   3
    19650104    0   1   3

I want to split and store it into two variables/dataframes based on whether the year is even or odd. 我想根据年份是偶数还是奇数将它拆分并存储到两个变量/数据帧中。

So basically, one dataframe/variable will have even years 所以基本上,一个数据帧/变量甚至会有几年

    19620101    1   2   4
    19640103    0   2   3

While another will have odd years: 而另一个将有奇数年:

    19630102    6   2   3
    19650104    0   1   3

How can I do this? 我怎样才能做到这一点?

> split(df, floor(df[[1]] / 1e4) %% 2 == 0)
$`FALSE`
        V1 V2 V3 V4
2 19630102  6  2  3
4 19650104  0  1  3

$`TRUE`
        V1 V2 V3 V4
1 19620101  1  2  4
3 19640103  0  2  3

If year is stored in four first characters of the first column, then 如果年份存储在第一列的四个第一个字符中,那么

split(d,as.numeric(substr(d$V1,1,4))%%2==0)

where d is a data.frame: 其中d是data.frame:

> d
        V1 V2 V3 V4
1 19620101  1  2  4
2 19630102  6  2  3
3 19640103  0  2  3
4 19650104  0  1  3

> dput(d)
structure(list(V1 = c(19620101L, 19630102L, 19640103L, 19650104L
), V2 = c(1L, 6L, 0L, 0L), V3 = c(2L, 2L, 2L, 1L), V4 = c(4L, 
3L, 3L, 3L)), .Names = c("V1", "V2", "V3", "V4"), class = "data.frame", row.names = c(NA, 
-4L))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM