Split a data frame into a list of blocks (either by rows or by columns)

df_to_blocks(DataFrame, blocks, byrow = TRUE)

Arguments

DataFrame

a data frame to split

blocks

either a list or a vector indicating the blocks. If blocks is a list of vectors, then the length of each vector defines the size of the blocks. If blocks is a vector, then each element represents the size of the blocks.

byrow

logical. If TRUE (the default) the data frame is split by rows, otherwise the data frame is split by columns

Value

A list of data frames

Author

Gaston Sanchez

See also

Examples

# say you have a data frame
iris_df = iris[c(1:3,51:53,101:103),]

# list defining the blocks
row_blocks = list(1:3, 4:6, 7:9)
col_blocks = c(2, 2, 1)

# split data into list of blocks (by rows)
df_to_blocks(iris_df, row_blocks)
#> [[1]]
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1          5.1         3.5          1.4         0.2  setosa
#> 2          4.9         3.0          1.4         0.2  setosa
#> 3          4.7         3.2          1.3         0.2  setosa
#> 
#> [[2]]
#>    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
#> 51          7.0         3.2          4.7         1.4 versicolor
#> 52          6.4         3.2          4.5         1.5 versicolor
#> 53          6.9         3.1          4.9         1.5 versicolor
#> 
#> [[3]]
#>     Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
#> 101          6.3         3.3          6.0         2.5 virginica
#> 102          5.8         2.7          5.1         1.9 virginica
#> 103          7.1         3.0          5.9         2.1 virginica
#> 

# split data into list of blocks (by columns)
df_to_blocks(iris_df, col_blocks, byrow=FALSE)
#> [[1]]
#>     Sepal.Length Sepal.Width
#> 1            5.1         3.5
#> 2            4.9         3.0
#> 3            4.7         3.2
#> 51           7.0         3.2
#> 52           6.4         3.2
#> 53           6.9         3.1
#> 101          6.3         3.3
#> 102          5.8         2.7
#> 103          7.1         3.0
#> 
#> [[2]]
#>     Petal.Length Petal.Width
#> 1            1.4         0.2
#> 2            1.4         0.2
#> 3            1.3         0.2
#> 51           4.7         1.4
#> 52           4.5         1.5
#> 53           4.9         1.5
#> 101          6.0         2.5
#> 102          5.1         1.9
#> 103          5.9         2.1
#> 
#> [[3]]
#> [1] setosa     setosa     setosa     versicolor versicolor versicolor virginica 
#> [8] virginica  virginica 
#> Levels: setosa versicolor virginica
#>