【问题标题】:Split matrix into columns and store in variables将矩阵拆分为列并存储在变量中
【发布时间】:2019-06-06 19:29:04
【问题描述】:

我有一个 n 行 d 列的矩阵。例如,

n = 100; d = 3
mat = matrix(rnorm(n * d) ncol = d)

我需要获取矩阵的列并将它们分配给变量 x1、x2、...、xd。列数不会固定。

我尝试拆分矩阵并使用 mapply 语句对其进行分配,但没有发生分配:

nam = paste0("x", 1:d)
column_vectors = split(x, rep(1:ncol(x), each = nrow(x)))
mapply(FUN = assign, nam, column_vectors)

我可以通过蛮力做到这一点,但必须有更简单、更清洁的方法。

nam = paste0("x", 1:d)
column_vectors = split(x, rep(1:ncol(x), each = nrow(x)))
for(i in seq_along(column_vectors)){

  assign(nam[i], column_vectors[[i]]) 
}

【问题讨论】:

    标签: r matrix data-manipulation


    【解决方案1】:

    你可以试试这个方法:

    matList <- unlist(apply(mat, 2, list),  recursive = FALSE)
    names(matList) <- paste0("x", 1:d)
    list2env(matList, envir = globalenv())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-17
      • 1970-01-01
      • 1970-01-01
      • 2015-03-16
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多