I'd like to get a function that sorts data frame in the way that equal numbers or 0 (/optionally NA) are in the same column.
It should look similar to this:
1 0 3 4 5
0 2 0 0 5
1 2 0 0 0
1 0 0 0 0
I'd like to get a function that sorts data frame in the way that equal numbers or 0 (/optionally NA) are in the same column.
It should look similar to this:
1 0 3 4 5
0 2 0 0 5
1 2 0 0 0
1 0 0 0 0
An option is to convert to data.frame
and bind with map_df
library(purrr)
library(dplyr)
map_df(z, as.data.frame) %>%
mutate_all(replace_na, 0)
Using just base R you could do this.
do.call(rbind, Map(function(z) {x <- t(apply(z, 1, `length<-`, l));x[is.na(x)] <- 0;x}, z))
# [,1] [,2] [,3] [,4]
# [1,] 1.3709584 0.0000000 0.0000000 0.0000000
# [2,] -0.5646982 0.0000000 0.0000000 0.0000000
# [3,] 0.3631284 0.0000000 0.0000000 0.0000000
# [4,] 0.6328626 0.0000000 0.0000000 0.0000000
# [5,] 1.3709584 -0.5646982 0.0000000 0.0000000
# [6,] 1.3709584 0.3631284 0.0000000 0.0000000
# [7,] 1.3709584 0.6328626 0.0000000 0.0000000
# [8,] -0.5646982 0.3631284 0.0000000 0.0000000
# [9,] -0.5646982 0.6328626 0.0000000 0.0000000
# [10,] 0.3631284 0.6328626 0.0000000 0.0000000
# [11,] 1.3709584 -0.5646982 0.3631284 0.0000000
# [12,] 1.3709584 -0.5646982 0.6328626 0.0000000
# [13,] 1.3709584 0.3631284 0.6328626 0.0000000
# [14,] -0.5646982 0.3631284 0.6328626 0.0000000
# [15,] 1.3709584 -0.5646982 0.3631284 0.6328626
Explanation: Essentially this is an rbind
problem where the matrices in list z
have different number of columns. Since the needed number of columns is known by l
we can take each single row of a matrix as a vector with apply()
and prolong it to l
with length<-
. Because this yields NA
s we need to convert these to the desired zeroes. Map
applies that to the whole list. Finally wrapping do.call(rbind..)
around it binds the listed matrices into a single one.
z <- list(structure(c(1.37095844714667, -0.564698171396089, 0.363128411337339,
0.63286260496104), .Dim = c(4L, 1L)), structure(c(1.37095844714667,
1.37095844714667, 1.37095844714667, -0.564698171396089, -0.564698171396089,
0.363128411337339, -0.564698171396089, 0.363128411337339, 0.63286260496104,
0.363128411337339, 0.63286260496104, 0.63286260496104), .Dim = c(6L,
2L)), structure(c(1.37095844714667, 1.37095844714667, 1.37095844714667,
-0.564698171396089, -0.564698171396089, -0.564698171396089, 0.363128411337339,
0.363128411337339, 0.363128411337339, 0.63286260496104, 0.63286260496104,
0.63286260496104), .Dim = 4:3), structure(c(1.37095844714667,
-0.564698171396089, 0.363128411337339, 0.63286260496104), .Dim = c(1L,
4L)))
l <- 4L