我有一个向量c(9,6,3,4,2,1,5,7,8)
,我想在向量中的索引2和索引5处切换元素.但是,我不想创建一个临时变量,并希望在一次调用中进行切换.我该怎么办?
jlh*_*ard 14
怎么样x[c(i,j)] <- x[c(j,i)]
?类似replace(...)
,但也许有点简单.
swtch <- function(x,i,j) {x[c(i,j)] <- x[c(j,i)]; x}
swtch(c(9,6,3,4,2,1,5,7,8) , 2,5)
# [1] 9 2 3 4 6 1 5 7 8
Run Code Online (Sandbox Code Playgroud)
Ric*_*ven 13
你可以用replace()
.
x <- c(9, 6, 3, 4, 2, 1, 5, 7, 8)
replace(x, c(2, 5), x[c(5, 2)])
# [1] 9 2 3 4 6 1 5 7 8
Run Code Online (Sandbox Code Playgroud)
如果你甚至不想分配x
,你可以使用
replace(
c(9, 6, 3, 4, 2, 1, 5, 7, 8),
c(2, 5),
c(9, 6, 3, 4, 2, 1, 5, 7, 8)[c(5, 2)]
)
# [1] 9 2 3 4 6 1 5 7 8
Run Code Online (Sandbox Code Playgroud)
但那有点傻.您可能希望x
分配开始.
如果您确实想在不创建向量的临时副本的情况下执行此操作,则需要编写一个简短的 C 函数。
library(inline)
swap <- cfunction(c(i = "integer", j = "integer", vec="integer"),"
int *v = INTEGER(vec);
int ii = INTEGER(i)[0]-1, jj = INTEGER(j)[0]-1;
int tmp = v[ii];
v[ii] = v[jj];
v[jj] = tmp;
return R_NilValue;
")
vec <- as.integer(c(9,6,3,4,2,1,5,7,8))
swap(2L, 5L, vec)
vec
# [1] 9 2 3 4 6 1 5 7 8
Run Code Online (Sandbox Code Playgroud)