how to combine vectors with different length within a list in R?

后端 未结 3 2024
故里飘歌
故里飘歌 2021-02-09 14:58

I have a problem when combining the following vectors included in the list:

x <- list(as.numeric(c(1,4)),as.numeric(c(3,19,11)))
names (x[[1]]) <- c(\"spec         


        
相关标签:
3条回答
  • 2021-02-09 15:42

    You need to give R a bit more help, by first preparing the particular vectors, all of the same length, that you eventually want to cbind together. Otherwise (as you've seen) R uses its usual recycling rules to fill out the matrix.

    Try something like this:

    spp <- paste("species", c("A", "B", "C"), sep=".")
    
    x2 <- lapply(x, FUN=function(X) X[spp])
    mat <- do.call("cbind", x2)
    row.names(mat) <- spp
    
    mat
              [,1] [,2]
    species.A    1    3
    species.B   NA   19
    species.C    4   11
    

    EDIT: As Brian mentions in comments, this could be made a bit more compact (but at the expense of some readability). Which one you use is just a matter of taste:

    mat <- do.call("cbind", lapply(x, "[", spp))
    row.names(mat) <- spp
    
    0 讨论(0)
  • It looks like you're actually trying to do a merge. As such, merge will work. You just have to tell it to merge on the names, and to keep all rows.

    do.call(merge, c(x, by=0, all=TRUE))   # by=0 and by="row.names" are the same
    

    (This will create a data frame rather than a matrix, but for most purposes that shouldn't be an issue.)

    0 讨论(0)
  • 2021-02-09 15:55
    merge(x = x[[1]], y = x[[2]], by = "names", all.y = TRUE)
    
    0 讨论(0)
提交回复
热议问题