简体   繁体   English

在 R 中构建特定的名称向量

[英]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 .我有n*m形式的变量x = (i,j,a,b)其中i,j=1,...,na,b=1,...,m We always have i<=j and a<=b .我们总是有i<=ja<=b

They form the rownames of a (sparse) matrix I want to build in R.它们形成了我想在 R 中构建的(稀疏)矩阵的行名。 For example, the first row would be called 1,1,1,1 and the second one would be 1,1,1,2 .例如,第一行将被称为1,1,1,1 ,第二行将被称为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 .由于i<=j不会调用任何行2,1,1,1 ,并且由于a<=b不会调用任何行1,2,3,2

How can I automatically set these rownames in the matrix.如何在矩阵中自动设置这些行名。 The order is not important.顺序并不重要。

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.但是您可以使用expand.grid()创建所有可能的组合,然后根据您的规则排除您不需要的组合。 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 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

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

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 = ' ')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM