Triss
Triss

Reputation: 581

R create list or matrix

If I repeat this code

x<-1:6
n<-40
M<-200
y<-replicate(M,as.numeric(table(sample(x,n,1))))
str(y)

sometimes R decide to create a matrix and sometimes it creates a list. Can you explain me the reason for that? How can I be sure that it is a matrix or a list?

If you chose M very small, for example 10, it will almost always create a matrix. If you chose M very large, for example 2000, it will create a list.

Upvotes: 1

Views: 154

Answers (2)

Pavlo
Pavlo

Reputation: 63

May be it will help [https://rafalab.github.io/dsbook/r-basics.html#data-types][1] Vectors in matrix have to be all the same type and length Vectors in list can contain elements of different classes and length Try this:

x<-1
y<-2:7
z<-matrix(x,y)
z<-list(x,y)

In first case you will get matrix 2 rows and 1 column because y vector is longer In the second case you will get a list with elements of different length. Also

str()

function is very useful. But you can find the class of object using

class()

function.

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388982

You get a list for cases when not all the numbers in x are sampled.

You can always return a list by using simplify = FALSE.

y <- replicate(M, as.numeric(table(sample(x,n,TRUE))), simplify = FALSE)

Also, you are using 1 to set replace argument. It is better to use logical argument i.e TRUE.


To return always a matrix, we can do :

sapply(y, `[`, x)

This will append NA's for values where length is unequal.

Upvotes: 2

Related Questions