Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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?

like image 308
maximusdooku Avatar asked Jan 16 '15 21:01

maximusdooku


Video Answer


2 Answers

> 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
like image 155
DatamineR Avatar answered Sep 19 '22 12:09

DatamineR


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))
like image 38
Marat Talipov Avatar answered Sep 20 '22 12:09

Marat Talipov