如何重新排列列表中的对象

时间:2018-05-08 07:29:13

标签: r list

考虑这个例子:

> POST /my-url/1573 HTTP/1.1
> Host: my-host
> User-Agent: curl/7.47.0
> Accept: */*
> Content-Length: 113
> Content-Type: application/x-www-form-urlencoded
> 
* upload completely sent off: 113 out of 113 bytes
< HTTP/1.1 200 OK
< Server: nginx
< Date: Tue, 08 May 2018 07:16:10 GMT
< Content-Type: text/html;charset=utf-8
< Transfer-Encoding: chunked
< Connection: keep-alive
< Keep-Alive: timeout=60
< Vary: Accept-Encoding
< X-XSS-Protection: 1
< X-Content-Type-Options: nosniff
< Strict-Transport-Security: max-age=31536000
< Cache-Control: max-age=10
< Content-Language: en-US
< X-Cached: MISS

如何将列表中的对象重新排列为list1 <- split(mtcars, mtcars$cyl) names(list1) [1] "4" "6" "8" 顺序

这应该是一项简单的任务,我似乎无法使用谷歌找到答案。

有什么想法吗?

2 个答案:

答案 0 :(得分:4)

我将使用更简单的列表,以便更容易看到发生了什么:

> list1 = list("4"="Four","6"="Six","8"="Eight")
> names(list1)
[1] "4" "6" "8"
> list1
$`4`
[1] "Four"

$`6`
[1] "Six"

$`8`
[1] "Eight"

然后使用单个方括号重新排序:

> list2 = list1[c("8","4","6")]
> list2
$`8`
[1] "Eight"

$`4`
[1] "Four"

$`6`
[1] "Six"

答案 1 :(得分:3)

您可以按照您想要的顺序简单地提供元素索引的向量,在这种情况下,您需要第三个元素,然后是第一个和第二个元素:

list1 <- list1[c(3, 1, 2)]

这将产生:

names(list1)
[1] "8" "4" "6"