将元素从数组的前面移动到R中的数组的后面

时间:2014-04-29 16:28:56

标签: r

是否有一种优雅的方式来采用像

这样的矢量
x = c("a", "b", "c", "d", "e")

并使其成为

x = c("b", "c", "d", "e", "a")

我做了:

x = c("a", "b", "c", "d", "e")
firstVal = x[1]
x = tail(x,-1)
x[length(x)+1] = firstVal
x
[1] "b" "c" "d" "e" "a"

它有效,但有点难看。

4 个答案:

答案 0 :(得分:6)

优雅是品味的问题, de gustibus non est disputandum

> x <- c("a", "b", "c", "d", "e")
> c(x[-1], x[1])
[1] "b" "c" "d" "e" "a"

以上是否让你开心? :)

答案 1 :(得分:4)

同意品味评论的问题。我个人的做法是:

x[c(2:length(x), 1)]

答案 2 :(得分:4)

过度杀伤时间:您可以考虑我的 shifter 或我的 moveMe 功能,这两项功能都属于我的GitHub SOfun 包。

以下是相关的例子:

shifter

这基本上是headtail方法:

## Specify how many values need to be shifted
shifter(x, 1)
# [1] "b" "c" "d" "e" "a"
shifter(x, 2)
# [1] "c" "d" "e" "a" "b"

## The direction can be changed too :-)
shifter(x, -1)
# [1] "e" "a" "b" "c" "d"

moveMe

这很有趣:

moveMe(x, "a last")
# [1] "b" "c" "d" "e" "a"

## Lots of options to move things around :-)
moveMe(x, "a after d; c first")
# [1] "c" "b" "d" "a" "e"

答案 3 :(得分:2)

当我进行基准测试时,我有一个想法同时使用headtail,但结果却是失败了。

c(tail(x, -1), head(x, 1))

我想我会分享结果,因为它们提供了丰富的信息。我还扩大了更大的载体,结果很有趣:

x <- c("a", "b", "c", "d", "e")  

gagolews <- function() c(x[-1], x[1])

senoro <- function() x[c(2:length(x), 1)]

tyler <- function() c(tail(x, -1), head(x, 1))

ananda <- function() shifter(x, 1)

user <-function(){
   firstVal = x[1]
   x = tail(x,-1)
   x[length(x)+1] = firstVal
   x
}


library(microbenchmark)
(op <- microbenchmark( 
    gagolews(),
    senoro(),
    tyler(),
    ananda(),
    user(),
times=100L))

## Unit: microseconds
##        expr    min     lq median     uq      max neval
##  gagolews()  1.400  1.867  2.333  2.799    5.132  1000
##    senoro()  1.400  1.867  2.333  2.334   10.730  1000
##     tyler() 37.320 39.187 40.120 41.519  135.287  1000
##    ananda() 39.653 41.519 42.452 43.386   69.043  1000
##      user() 24.259 25.658 26.591 27.058 1757.789  1000

enter image description here 我在这里扩大规模。由于矢量的大小(100万个字符),我只进行了100次重复。

x <- rep(c("a", "b", "c", "d", "e"), 1000000)

## Unit: milliseconds
##        expr      min       lq   median       uq      max neval
##  gagolews() 168.9151 171.3631 179.0490 193.9604 260.5963   100
##    senoro() 192.2669 203.9596 259.1366 272.5570 341.4443   100
##     tyler() 237.4218 246.5368 303.5700 319.3999 347.3610   100
##    ananda() 237.9610 247.2097 303.9898 318.4564 342.2518   100
##      user() 225.4503 234.3431 287.8348 300.8078 319.2051   100

enter image description here