How to split a data frame?

后端 未结 8 2211
臣服心动
臣服心动 2020-11-22 03:08

I want to split a data frame into several smaller ones. This looks like a very trivial question, however I cannot find a solution from web search.

相关标签:
8条回答
  • 2020-11-22 03:36

    The answer you want depends very much on how and why you want to break up the data frame.

    For example, if you want to leave out some variables, you can create new data frames from specific columns of the database. The subscripts in brackets after the data frame refer to row and column numbers. Check out Spoetry for a complete description.

    newdf <- mydf[,1:3]
    

    Or, you can choose specific rows.

    newdf <- mydf[1:3,]
    

    And these subscripts can also be logical tests, such as choosing rows that contain a particular value, or factors with a desired value.

    What do you want to do with the chunks left over? Do you need to perform the same operation on each chunk of the database? Then you'll want to ensure that the subsets of the data frame end up in a convenient object, such as a list, that will help you perform the same command on each chunk of the data frame.

    0 讨论(0)
  • 2020-11-22 03:37

    I just posted a kind of a RFC that might help you: Split a vector into chunks in R

    x = data.frame(num = 1:26, let = letters, LET = LETTERS)
    ## number of chunks
    n <- 2
    dfchunk <- split(x, factor(sort(rank(row.names(x))%%n)))
    dfchunk
    $`0`
       num let LET
    1    1   a   A
    2    2   b   B
    3    3   c   C
    4    4   d   D
    5    5   e   E
    6    6   f   F
    7    7   g   G
    8    8   h   H
    9    9   i   I
    10  10   j   J
    11  11   k   K
    12  12   l   L
    13  13   m   M
    
    $`1`
       num let LET
    14  14   n   N
    15  15   o   O
    16  16   p   P
    17  17   q   Q
    18  18   r   R
    19  19   s   S
    20  20   t   T
    21  21   u   U
    22  22   v   V
    23  23   w   W
    24  24   x   X
    25  25   y   Y
    26  26   z   Z
    

    Cheers, Sebastian

    0 讨论(0)
提交回复
热议问题