Combine vectors of different lengths into a matrix one by one

Suppose we have the following three vectors.

L = c("1", "3")
K = c("2", "9", "2:9")
S = c("7")

Is there a way to combine them into a matrix that will look higher?

L    K    S
1    0    0
3    0    0
0    2    0
0    9    0
0    2:9  0
0    0    7

Thank.

+4
source share
3 answers

. , , , , . mapply ( ) . . ( ) 0.

l1 <- list(L, K, S)
m1 <- matrix(unlist(l1), nrow = sum(lengths(l1)), ncol = length(l1))
m1[!mapply(`%in%`, as.data.frame(m1), l1)] <- 0

m1
#     [,1] [,2]  [,3]
#[1,] "1"  "0"   "0" 
#[2,] "3"  "0"   "0" 
#[3,] "0"  "2"   "0" 
#[4,] "0"  "9"   "0" 
#[5,] "0"  "2:9" "0" 
#[6,] "0"  "0"   "7"

, , , , . , , i.e.

create_mat <- function(list){
  m1 <- matrix(unlist(list), nrow = sum(lengths(list)), ncol = length(list))
  m2 <- matrix(seq(nrow(m1)), ncol = ncol(m1), nrow = nrow(m1))
  l2 <- lapply(lengths(list), seq)
  v2 <- c(0, head(cumsum(lengths(list)), -1))
  l2 <-  Map(`+`, l2, v2)
  m1[!mapply(`%in%`, as.data.frame(m2), l2)] <- 0
  return(m1)
}

# Test with some values being same for multiple vectors,
M = c("1", "3")
N = c("1", "9", "2:9")
P = c("3")

create_mat(list(M, N, P))

#     [,1] [,2]  [,3]
#[1,] "1"  "0"   "0" 
#[2,] "3"  "0"   "0" 
#[3,] "0"  "1"   "0" 
#[4,] "0"  "9"   "0" 
#[5,] "0"  "2:9" "0" 
#[6,] "0"  "0"   "3" 
+2

: 0s, , k 1:l, .

l = length(c(L,K,S))
k = rep(1:3,times=c(length(L),length(K),length(S)))
m = matrix(0,ncol=3,nrow=l)
m[cbind(1:l,k)] = c(L,K,S)
     [,1] [,2]  [,3]
[1,] "1"  "0"   "0" 
[2,] "3"  "0"   "0" 
[3,] "0"  "2"   "0" 
[4,] "0"  "9"   "0" 
[5,] "0"  "2:9" "0" 
[6,] "0"  "0"   "7" 

: , , @DavidArenburg, :

l = list(L,K,S)
len = length(unlist(l))
k = rep(seq_along(l), lengths(l))
m = matrix(0, nrow=len, ncol=length(l))
m[cbind(1:len, k)] = unlist(l)
+4
library(dplyr)

L = c("1", "3")
K = c("2", "9", "2:9")
S = c("7")

Ltable <- tibble(L=L)
Ktable <- tibble(K=K)
Stable <- tibble(S=S)
JoinedMatrix <- Ltable %>% bind_rows(Ktable) %>% bind_rows(Stable) %>% as.matrix() 
JoinedMatrix[which(is.na(JoinedMatrix))] <- "0"

bind_rowsof dplyrallows you to bind data (or pins) together. Since the three columns have differently named columns, they are saved as different columns after merging, filling in the missing fields NA. After that, we just replace everything NAwith 0, and we are done.

> JoinedMatrix
     L   K     S  
[1,] "1" "0"   "0"
[2,] "3" "0"   "0"
[3,] "0" "2"   "0"
[4,] "0" "9"   "0"
[5,] "0" "2:9" "0"
[6,] "0" "0"   "7"
+1
source

Source: https://habr.com/ru/post/1681071/


All Articles