我有這樣如何在一個特定的格式
seq_vector <- c(3,12,5,9,11,8,4,6,7,11,15,3,9,10,12,2)
我想他們在降奇數,其次是上升偶數階命令格式的矢量陣列的奇數和偶數排序。以上seq_vector的輸出將是
new_seq_vector <- c(15,11,11,9,9,7,5,3,3,2,4,6,8,10,12,12)
你能幫我一樣的邏輯嗎?
我有這樣如何在一個特定的格式
seq_vector <- c(3,12,5,9,11,8,4,6,7,11,15,3,9,10,12,2)
我想他們在降奇數,其次是上升偶數階命令格式的矢量陣列的奇數和偶數排序。以上seq_vector的輸出將是
new_seq_vector <- c(15,11,11,9,9,7,5,3,3,2,4,6,8,10,12,12)
你能幫我一樣的邏輯嗎?
嘗試x[order(x*v)]
其中v
是-1奇,一爲偶數。
感謝@lmo此:
x[order(x*(-1)^x)]
# [1] 15 11 11 9 9 7 5 3 3 2 4 6 8 10 12 12
所以v = (-1)^x
這裏。
一些其他的方法來建立v
:@ d.b的(-1)^(x %% 2)
;和我的,1-2*(x %% 2)
。
(感謝@ d.b)如果x
包含負整數,需要額外的排序向量:
# new example
x = c(2, 5, -15, -10, 1, -3, 12)
x[order(v <- (-1)^x, x*v)]
# [1] 5 1 -3 -15 -10 2 12
取模數2(%% 2
)來相應地確定奇數和偶數元素和sort
。
c(sort(seq_vector[seq_vector %% 2 == 1], decreasing = TRUE), #For odd
sort(seq_vector[seq_vector %% 2 == 0])) #For even
#[1] 15 11 11 9 9 7 5 3 3 2 4 6 8 10 12 12
使用輔助功能。
is.odd <- function(x) (x %% 2) == 1
result <- c(sort(seq_vector[is.odd(seq_vector)], decreasing = TRUE),
sort(seq_vector[!is.odd(seq_vector)]))
result
@ d.b我編寫和測試我的答案,當你發佈你的。所以我只看到它後。 –
謝謝Rui Barradas :) – vinodetrx
另外'seq_vector [order(seq_vector *(-1)^ seq_vector)]'。 – lmo
@lmo,這是聰明的 –
@ d.b謝謝。這些都是有趣的謎題。 – lmo