2

Recording vectors of different lengths in a matrix / data frame

 2 years ago
source link: https://www.codesd.com/item/recording-vectors-of-different-lengths-in-a-matrix-data-frame.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Recording vectors of different lengths in a matrix / data frame

advertisements

I have a numeric called area of length 166860. This consists of 412 different elements, most of length 405 and some of length 809. I have their start and end ids.

My goal is to extract them and put them in a matrix/data frame with 412 columns

Right now, I'm trying this code:

m = matrix(NA,ncol=412, nrow=809)
for (j in 1:412){
temp.start = start.ids[j]
temp.end = end.ids[j]
m[,j] = area[temp.start:temp.end]
}

But I just end up with this error message:

"Error in m[, j] = area[temp.start:temp.end] : number of items to replace is not a multiple of replacement length"


Here's a quite easy approach:

Example data:

area <- c(1:4, 1:5, 1:6, 1:3)
# [1] 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 1 2 3

start.ids <- which(area == 1)
# [1]  1  5 10 16

end.ids <- c(which(area == 1)[-1] - 1, length(area))
# [1]  4  9 15 18

Create a list with one-row matrices:

mats <- mapply(function(x, y) t(area[seq(x, y)]), start.ids, end.ids)
# [[1]]
#      [,1] [,2] [,3] [,4]
# [1,]    1    2    3    4
#
# [[2]]
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    2    3    4    5
#
# [[3]]
#      [,1] [,2] [,3] [,4] [,5] [,6]
# [1,]    1    2    3    4    5    6
#
# [[4]]
#      [,1] [,2] [,3]
# [1,]    1    2    3

Use the function rbind.fill.matrix from the plyr package to create the matrix and transpose it (t):

library(plyr)
m <- t(rbind.fill.matrix(mats))
#    [,1] [,2] [,3] [,4]
# 1    1    1    1    1
# 2    2    2    2    2
# 3    3    3    3    3
# 4    4    4    4   NA
# 5   NA    5    5   NA
# 6   NA   NA    6   NA


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK