gpt4 book ai didi

Change row order in a matrix/dataframe with pipes(使用管道更改矩阵/数据帧中的行顺序)

转载 作者:bug小助手 更新时间:2023-10-24 17:10:47 25 4
gpt4 key购买 nike



I have some matrix or dataframe

我有一些矩阵或数据帧


m <- matrix(1:6, ncol=2) 

..

。。


m
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6

i need to change order rows in a line with pipes, something like this

我需要更改带有管道的一行中的顺序行,如下所示


m |> m[nrow(m):1, ]

but of course it doesn't work..

但它当然不起作用..


I know that I can do this using the dplyr package

我知道我可以使用dplyr包来做到这一点


library(dplyr)
m |> as.data.frame() |> arrange(-row_number())

But I'm wondering how to do this with base R.

但我想知道如何在R基地做到这一点。


更多回答

One completely pointless option - m |> (\(x) x[nrow(x):1,])()

一个完全没有意义的选项-m|>(\(X)x[nrow(X):1,])()

优秀答案推荐

Using i= and j= operators of the bracket function.

使用括号函数的i=和j=运算符。


m |> base::`[`(3:1, )
# [,1] [,2]
# [1,] 3 6
# [2,] 2 5
# [3,] 1 4

Generalized:

泛指:


m |> base::`[`(dim(m)[1]:1, )
# [,1] [,2]
# [1,] 3 6
# [2,] 2 5
# [3,] 1 4

Note: Contributions also come from @thelatemail and @ThomasIsCoding.

注:投稿也来自@thelatmail和@ThomasIsCoding。




Data:

数据:


m <- structure(1:6, dim = 3:2)



The RHS of the base-R |> pipe must be a function, you can't use m[...] on the RHS at all. However ... `[`(..) (despite being a function call) explicitly does not work (Error: function '[' not supported in RHS call of a pipe).

Base-R|>管道的RHS必须是函数,不能使用m[...]在皇家医疗服务体系上。然而...`[`(..)(尽管是函数调用)显式不起作用(错误:管道的RHS调用不支持Function‘[’)。


A (hasty, untested) hack-function might be:

一个(仓促的、未经测试的)黑客功能可能是:


fn <- function(x, i=NULL, j=NULL) x[if (is.null(i)) seq_len(nrow(x)) else i, if (is.null(j)) seq_len(ncol(x)) else j]
m |>
fn(nrow(m):1)
# [,1] [,2]
# [1,] 3 6
# [2,] 2 5
# [3,] 1 4

... though I'm sure there are corner-cases where this may not work perfectly.

..。不过,我敢肯定,在某些情况下,这种方法可能不会完美地发挥作用。


更多回答

I guess you can simply apply m |> base::`[`(nrow(m):1, )

我想您可以简单地应用m|>base::`[`(nrow(M):1,)

@ThomasIsCoding TY, letting j default was actually obvious and removed overhead, your comma did the trick! dim is faster than nrow.

@ThomasIsCoding Ty,让j默认实际上是显而易见的,并且去掉了头顶,你的逗号做到了!Dim比Nrow快。

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