Claudio Moneo
Claudio Moneo

Reputation: 569

Building a particular vector of names in R

I have n*m variables of the form x = (i,j,a,b) where i,j=1,...,n and a,b=1,...,m. We always have i<=j and a<=b.

They form the rownames of a (sparse) matrix I want to build in R. For example, the first row would be called 1,1,1,1 and the second one would be 1,1,1,2. No row will be called 2,1,1,1 since i<=j and similiarly no row will be called 1,2,3,2 since a<=b.

How can I automatically set these rownames in the matrix. The order is not important.

Upvotes: 0

Views: 44

Answers (3)

Gowachin
Gowachin

Reputation: 1270

here is an attempt to solution your question :

n = 2
m = 2
i = 1
a = 1

df <- expand.grid(i:n, i:n, a:m, a:m)
df[ !(df$Var1 > df$Var2 | df$Var3 > df$Var4) ,]
apply(df, 1, paste,  collapse = ' ')

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 101343

Perhaps you can try the code below

n <- 2
m <- 3

p <- subset(expand.grid(rep(list(seq(n)), 2)), Var1 <= Var2)
q <- subset(expand.grid(rep(list(seq(m)), 2)), Var1 <= Var2)

with(
  expand.grid(1:nrow(p), 1:nrow(q)),
  cbind(p[Var1, ], q[Var2, ])
)

which gives

    Var1 Var2 Var1 Var2
1      1    1    1    1
3      1    2    1    1
4      2    2    1    1
1.1    1    1    1    2
3.1    1    2    1    2
4.1    2    2    1    2
1.2    1    1    2    2
3.2    1    2    2    2
4.2    2    2    2    2
1.3    1    1    1    3
3.3    1    2    1    3
4.3    2    2    1    3
1.4    1    1    2    3
3.4    1    2    2    3
4.4    2    2    2    3
1.5    1    1    3    3
3.5    1    2    3    3

Upvotes: 0

Damian
Damian

Reputation: 1433

Making up some data here. But you can create all the possible combinations using expand.grid() then exclude the combinations you don't need based on your rule. Then construct a character vector, and then use it as the labels for the row names of the matrix.

X <- expand.grid(i = 1:3,
            j = 1:3,
            a = 1:3,
            b = 1:3) %>%
    filter(i <= j & a <= b) %>%
    mutate(label = paste(i, j, a, b, sep = ",")) %>%
    pull(label)

matrix(data = NA, nrow = length(X), ncol = 4, dimnames = list(X))

First few rows of output

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

Upvotes: 1

Related Questions