replacing data frame row values with a shorter vector and fill other cells with 0s

Hello to everyone!

I want to combine all samples (with different rows and columns) into one matrix, but when I’m trying to assign samples to empty combined matrix I have gotten this error:

“error number of items to replace is not a multiple of replacement length”

I was wondering can I add zeros to other samples to avoid this error.

Can you help me with how to proceed?

Here the code that I wrote:

# unique taxa of all data
all.genus <- c("taxa1","taxa2","taxa3","taxa4",
               "taxa5","taxa6","taxa7","taxa8") 

# unique samples of all data
all.samples <- c("sample1.1", "sample1.2", "sample1.3","sample2.1","sample2.2","sample2.3",
                 "sample3.1","sample3.2") 

# creating matrix which containing all unique samples and taxa
combined.data = matrix(0, nrow = 8, ncol = 8)
rownames(combined.data) = all.genus
colnames(combined.data) = all.samples

# real sample1 which containing "sample1.1","sample1.2", "sample1.3"
sample1 <- matrix(runif(12), nrow = 4, ncol = 3)
colnames(sample1) = c("sample1.1", "sample1.2", "sample1.3")
rownames(sample1) = c("taxa1","taxa4","taxa5","taxa7")

# loop for assingn sample1data to combined.data
for(i in all.genus) {
  ind = which(rownames(sample1) == i)
  replace.data <- sample1[ind,]
  combined.data[i,] = replace.data
}

Read more here: Source link