Efficient transpose of list
transpose.Rdtranspose is an efficient way to transpose lists, data.frames or data.tables.
Arguments
- l
A list, data.frame or data.table.
- fill
Default is
NA. It is used to fill shorter list elements so as to return each element of the transposed result of equal lengths.- ignore.empty
Default is
FALSE.TRUEwill ignore length-0 list elements.- keep.names
The name of the first column in the result containing the names of the input; e.g.
keep.names="rn". By defaultNULLand the names of the input are discarded.- make.names
The name or number of a column in the input to use as names of the output; e.g.
make.names="rn". By defaultNULLand default names are given to the output columns.- list.cols
Default is
FALSE.TRUEwill avoid promoting types and return columns of typelistinstead.factorwill always be cast tocharacter.
Details
The list elements (or columns of data.frame/data.table) should be all atomic. If list elements are of unequal lengths, the value provided in fill will be used so that the resulting list always has all elements of identical lengths. The class of input object is also preserved in the transposed result.
The ignore.empty argument can be used to skip or include length-0 elements.
This is particularly useful in tasks that require splitting a character column and assigning each part to a separate column. This operation is quite common enough that a function tstrsplit is exported.
factor columns are converted to character type. Attributes are not preserved at the moment. This may change in the future.
Value
A transposed list, data.frame or data.table.
list outputs will only be named according to make.names.
Examples
ll = list(1:5, 6:8)
transpose(ll)
#> [[1]]
#> [1] 1 6
#>
#> [[2]]
#> [1] 2 7
#>
#> [[3]]
#> [1] 3 8
#>
#> [[4]]
#> [1] 4 NA
#>
#> [[5]]
#> [1] 5 NA
#>
setDT(transpose(ll, fill=0))[]
#> V1 V2 V3 V4 V5
#> <int> <int> <int> <int> <int>
#> 1: 1 2 3 4 5
#> 2: 6 7 8 0 0
DT = data.table(x=1:5, y=6:10)
transpose(DT)
#> V1 V2 V3 V4 V5
#> <int> <int> <int> <int> <int>
#> 1: 1 2 3 4 5
#> 2: 6 7 8 9 10
DT = data.table(x=1:3, y=c("a","b","c"))
transpose(DT, list.cols=TRUE)
#> V1 V2 V3
#> <list> <list> <list>
#> 1: 1 2 3
#> 2: a b c
# base R equivalent of transpose
l = list(1:3, c("a", "b", "c"))
lapply(seq(length(l[[1]])), function(x) lapply(l, `[[`, x))
#> [[1]]
#> [[1]][[1]]
#> [1] 1
#>
#> [[1]][[2]]
#> [1] "a"
#>
#>
#> [[2]]
#> [[2]][[1]]
#> [1] 2
#>
#> [[2]][[2]]
#> [1] "b"
#>
#>
#> [[3]]
#> [[3]][[1]]
#> [1] 3
#>
#> [[3]][[2]]
#> [1] "c"
#>
#>
transpose(l, list.cols=TRUE)
#> [[1]]
#> [[1]][[1]]
#> [1] 1
#>
#> [[1]][[2]]
#> [1] "a"
#>
#>
#> [[2]]
#> [[2]][[1]]
#> [1] 2
#>
#> [[2]][[2]]
#> [1] "b"
#>
#>
#> [[3]]
#> [[3]][[1]]
#> [1] 3
#>
#> [[3]][[2]]
#> [1] "c"
#>
#>
ll = list(nm=c('x', 'y'), 1:2, 3:4)
transpose(ll, make.names="nm")
#> $x
#> [1] 1 3
#>
#> $y
#> [1] 2 4
#>