Search code examples
rdata-cleaning

Split a dataframe in two different dataframes


I'm working in a data cleaning with R, I'm on my first steps, and I want to divide a dataframe "df" in two different dataframes (df1,df2) of the same size, by rows. I don't know the number of rows of the dataframe, here's what I need:

df:
NAME    BIRTH             AGE
Joseph    6/2/1988         28
Jessica   16/3/1975        41
#CONVERT TO 2 DATA FRAMES
df1:
NAME    BIRTH             AGE
Joseph    6/2/1988         28

df2:
NAME    BIRTH             AGE
Jessica   16/3/1975        41

Thanks in advance.


Solution

  • This should work:

        index = floor(nrow(df)/2)
        df1 = df[1:index,]
        df2 = df[(index +1) : nrow(df),]
    

    It will split your original df into two equal dataframe df1 and df2 in case of nrow(df) = even and df1 will have 1 row less than df2 in case of nrow(df) = odd