Create a matrix without repeating the values of the date argument

Asked

Viewed 87 times

2

Hello, I have the following code

M <- matrix(data = c(1,2,3,4,5), nrow = 5, ncol = 5, T)

It produces the following output:

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    1    2    3    4    5
[3,]    1    2    3    4    5
[4,]    1    2    3    4    5
[5,]    1    2    3    4    5

I want the array to be created in a way that uses the values of the given array as date, but not to repeat the array afterwards, but to complete the values not provided with NA, being as follows:

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]   NA   NA   NA   NA   NA
[3,]   NA   NA   NA   NA   NA
[4,]   NA   NA   NA   NA   NA
[5,]   NA   NA   NA   NA   NA

I know you can do this by creating a matrix with data = NA and then loop the matrix, but wanted to know a faster and more efficient way to do.

2 answers

3


This is what occurs in R is called recycling (repetition of values to complete the vector). You can solve this situation by adjusting the vector outside the function matrix or inside it. Here are the two ways:

Vector adjustment outside function

x <- 1:5

It means that x goes from 1 to 5. Now, consider this:

length(x) <- prod(dim(matrix(x, ncol = 5, nrow = 5)))

Or just that:

length(x) <- prod(5, 5)

Or this:

length(x) <- 25

This means that the length of the vector is equal to 5x5 = 25. But as x goes from 1 to 5, the vector will be completed with NAs:

x

#[1]  1  2  3  4  5 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA

Now, put this vector as a parameter in the argument data:

M <- matrix(data = x, nrow = 5, ncol = 5, byrow = TRUE)

M

#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    2    3    4    5
# [2,]   NA   NA   NA   NA   NA
# [3,]   NA   NA   NA   NA   NA
# [4,]   NA   NA   NA   NA   NA
# [5,]   NA   NA   NA   NA   NA

Adjustment of the vector within the function

Another option is to create the data within the function matrix. Thus:

matrix(data = c(1:5, rep(c(NA), times = 20)), nrow = 5, ncol = 5, byrow = TRUE)

#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    2    3    4    5
# [2,]   NA   NA   NA   NA   NA
# [3,]   NA   NA   NA   NA   NA
# [4,]   NA   NA   NA   NA   NA
# [5,]   NA   NA   NA   NA   NA

2

In addition to @neves' very thorough answer, I wanted to draw attention to something that is in the question (my emphasis):

I know you can do this by creating a matrix with data = NA and then loop at headquarters, but wanted to know a faster way and more efficient to do.

R is a vector language, in this case, as in many others, it is not necessary to make loops.

M <- matrix(NA, nrow = 5, ncol = 5)
M[1, ] <- 1:5

M
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    1    2    3    4    5
#[2,]   NA   NA   NA   NA   NA
#[3,]   NA   NA   NA   NA   NA
#[4,]   NA   NA   NA   NA   NA
#[5,]   NA   NA   NA   NA   NA

Browser other questions tagged

You are not signed in. Login or sign up in order to post.