从向量创建矩阵并使用基管翻转它

Tol*_*ene 5 r

我有以下向量:

v<-c(1,2,3,4,1,2,3,4,2) 
Run Code Online (Sandbox Code Playgroud)

我想将其“转换”为 3x3 矩阵:

matrix <- matrix(data=v,ncol=3)
Run Code Online (Sandbox Code Playgroud)

然后我想“翻转”(不是转置)

flip_matrix<-matrix[,3:1,drop=FALSE]
Run Code Online (Sandbox Code Playgroud)

使用 tidyverse 管道来链接所有这些非常容易,但为了减少依赖关系,我想使用基本 R 来解决这个问题。我可以创建多个对象并忘记管道,但我需要知道这是如何实现的与基管一起完成。到目前为止,我没有运气:

v<-c(1,2,3,4,1,2,3,4,2)

final_matrix <- matrix(data=v,ncol=3) |> .[,3:1.drop=FALSE]()
Run Code Online (Sandbox Code Playgroud)

这告诉我对象“。” 没找到。我尝试过其他迭代但没有运气......感谢您的帮助!

GKi*_*GKi 8

调用该函数的另一种方式[

v <- c(1,2,3,4,1,2,3,4,2)

matrix(data=v,ncol=3) |> `[`(x=_,,3:1, drop = FALSE)
#     [,1] [,2] [,3]
#[1,]    3    4    1
#[2,]    4    1    2
#[3,]    2    2    3
Run Code Online (Sandbox Code Playgroud)

或不带占位符:

#Does not work as '[' is currently not supported in RHS call of a pipe
#matrix(data=v,ncol=3) |> `[`(,3:1, drop = FALSE)

#But the following will currently work
matrix(data=v,ncol=3) |> base::`[`(,3:1, drop = FALSE)
matrix(data=v,ncol=3) |> (`[`)(,3:1, drop = FALSE)
Run Code Online (Sandbox Code Playgroud)

或者不带管道:

matrix(data=v,ncol=3)[, 3:1, drop = FALSE]
#matrix(v, ncol=3)[, 3:1] #Short alternative
Run Code Online (Sandbox Code Playgroud)

  • 我想说*没有管道*是迄今为止最干净的。 (2认同)