gpt4 book ai didi

r - 主对角线变为反对角线

转载 作者:行者123 更新时间:2023-12-02 04:44:34 28 4
gpt4 key购买 nike

我需要变换主对角线

{matrix(
1 1 1 1,
0 2 2 2,
0 0 3 3,
0 0 0 4)
}

进入:

{matrix(
0 0 0 1,
0 0 1 2,
0 1 2 3,
1 2 3 4)
}

我尝试了我能找到的所有运算符 t()arev()flipud()apply(x, 2,rev)等。没有积极的结果。希望你能帮助我。

最佳答案

这对你有用吗?获取每一列并“旋转”(找不到更好的词)x 个位置,其中 x 是列索引。

res <- sapply(1:ncol(input),function(x){
#get relevant column
base <- input[,x]
n <- length(base)
indices <- 1:n
#reshuffle indices: first above x, then below x
out <- base[c(indices[indices>x],indices[indices<=x])]
out
})

all(res==output)
[1] TRUE

使用的数据:

input <- structure(c(1, 0, 0, 0, 1, 2, 0, 0, 1, 2, 3, 0, 1, 2, 3, 4), .Dim = c(4L, 
4L))
output <- structure(c(0, 0, 0, 1, 0, 0, 1, 2, 0, 1, 2, 3, 1, 2, 3, 4), .Dim = c(4L,
4L))

关于r - 主对角线变为反对角线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34289849/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com