【问题标题】:Can I have a vector of vectors in R我可以在 R 中有一个向量的向量吗
【发布时间】:2017-02-14 11:52:40
【问题描述】:

s 的范围从 -2 到 2 乘以 0.1 时,我想产生所有可能的 w,其中 w_minw_max 是 5 x 1 向量。但我不知道如何表示结果。我想我也需要一个向量,每个元素都作为向量,即向量的向量。

s <- seq(-2, 2, by = 0.1)

result = c()

for (i in 1:20) {
   w = s[i] * w_min + (1 - s[i]) * w_max
   ## what do I need to do here??
   }

result

【问题讨论】:

    标签: r vector sequence


    【解决方案1】:

    您需要一个矩阵,其中有很多列,而每列都是一个向量


    为了提供一个玩具示例,我需要让你的 "w_minw_max 是 5 * 1 个向量" 具体:

    ## note, they are just plain vectors without dimension
    ## if you have a `5 * 1` matrix, use `c(w_min)` and `c(w_max)` to drop dimension
    w_min <- 1:5
    w_max <- 2:6
    

    另外,为了使示例更小,我将考虑s &lt;- seq(-2, 2, by = 1) 与步骤1

    首先,考虑基于循环的方法:

    w <- matrix(0, 5, length(s))  ## set up a `5 * length(s)` matrix
    for (i in 1:length(s)) {
      ## fill i-th column of the matrix
      w[, i] <- s[i] * w_min + (1 - s[i]) * w_max
      }
    
    w
    #     [,1] [,2] [,3] [,4] [,5]
    #[1,]    4    3    2    1    0
    #[2,]    5    4    3    2    1
    #[3,]    6    5    4    3    2
    #[4,]    7    6    5    4    3
    #[5,]    8    7    6    5    4
    

    那么,向量化方法:

    ## read `?outer`; the default function to apply is `FUN = "*"` for multiplication
    w <- outer(w_min, s) + outer(w_max, 1 - s)
    
    w
    #     [,1] [,2] [,3] [,4] [,5]
    #[1,]    4    3    2    1    0
    #[2,]    5    4    3    2    1
    #[3,]    6    5    4    3    2
    #[4,]    7    6    5    4    3
    #[5,]    8    7    6    5    4
    

    除了矩阵,您还可以将结果存储在向量列表中。

    w <- vector("list", length(s))  ## set up a `length(s)` list
    for (i in 1:length(s)) {
      ## fill i-th element of the list; note the `[[i]]`
      w[[i]] <- s[i] * w_min + (1 - s[i]) * w_max
      }
    
    w
    #[[1]]
    #[1] 4 5 6 7 8
    #
    #[[2]]
    #[1] 3 4 5 6 7
    #
    #[[3]]
    #[1] 2 3 4 5 6
    #
    #[[4]]
    #[1] 1 2 3 4 5
    #
    #[[5]]
    #[1] 0 1 2 3 4
    

    但这里没有真正的矢量化方法。我们最多可以通过lapply 隐藏循环:

    w <- lapply(s, function (x) x * w_min + (1 - x) * w_max)
    
    w
    #[[1]]
    #[1] 4 5 6 7 8
    #
    #[[2]]
    #[1] 3 4 5 6 7
    #
    #[[3]]
    #[1] 2 3 4 5 6
    #
    #[[4]]
    #[1] 1 2 3 4 5
    #
    #[[5]]
    #[1] 0 1 2 3 4
    

    【讨论】:

      猜你喜欢
      • 2019-11-13
      • 1970-01-01
      • 1970-01-01
      • 2013-08-12
      • 1970-01-01
      • 2020-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多