简体   繁体   中英

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
        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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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