Às 11:46 de 26/06/2025, Steven Yen escreveu:
I'd like to cbind matrices of different number of rows, with missing values filled by 
"NA". I used dplyr. The following is obviously not working. Help appreciated.

library(dplyr)
a<-matrix(1:12,nrow=6); a
      [,1] [,2]
[1,]    1    7
[2,]    2    8
[3,]    3    9
[4,]    4   10
[5,]    5   11
[6,]    6   12
b<-matrix(5:12,nrow=4); b
      [,1] [,2]
[1,]    5    9
[2,]    6   10
[3,]    7   11
[4,]    8   12
cbind.fill(a,b)
Error in cbind.fill(a, b) : could not find function "cbind.fill"

Steven from iPhone
        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide https://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Hello,

The error message says that though you have dplyr loaded, R cannot find cbind.ill. This means that that function is not a dplyr function. A google search found rowr::cbind.fill but package rowr is not available for R 4.5.0. Abandonware?

Program your own cbind.fill.



cbind.fill <- function(...) {
  dots <- list(...)
  i <- sapply(dots, \(x) inherits(x, "matrix"))
  dots <- dots[i]
  mx <- max(sapply(dots, nrow))
  out_list <- lapply(dots, \(x) {
    if(nrow(x) < mx)
      x <- rbind(x, matrix(nrow = mx - nrow(x), ncol = ncol(x)))
    x
  })
  do.call(cbind, out_list)
}

a<-matrix(1:12,nrow=6)
b<-matrix(5:12,nrow=4)

cbind.fill(a, b)
#>      [,1] [,2] [,3] [,4]
#> [1,]    1    7    5    9
#> [2,]    2    8    6   10
#> [3,]    3    9    7   11
#> [4,]    4   10    8   12
#> [5,]    5   11   NA   NA
#> [6,]    6   12   NA   NA
cbind.fill(b, a, b)
#>      [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,]    5    9    1    7    5    9
#> [2,]    6   10    2    8    6   10
#> [3,]    7   11    3    9    7   11
#> [4,]    8   12    4   10    8   12
#> [5,]   NA   NA    5   11   NA   NA
#> [6,]   NA   NA    6   12   NA   NA
cbind.fill(b, a, b, a[1:5, ])
#>      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
#> [1,]    5    9    1    7    5    9    1    7
#> [2,]    6   10    2    8    6   10    2    8
#> [3,]    7   11    3    9    7   11    3    9
#> [4,]    8   12    4   10    8   12    4   10
#> [5,]   NA   NA    5   11   NA   NA    5   11
#> [6,]   NA   NA    6   12   NA   NA   NA   NA



(Then I found [1], with a version of cbind.fill equivalent to mine.)

[1] https://stackoverflow.com/a/7962286/8245406


Hope this helps,

Rui Barradas



--
Este e-mail foi analisado pelo software antivírus AVG para verificar a presença 
de vírus.
www.avg.com

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide https://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to