inplace修改R中的向量

Sar*_*ang 0 r vector

我在R中有一个矢量'参与者'

> participant
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
Run Code Online (Sandbox Code Playgroud)

我正在使用函数'modify'来更改此向量的内容.

modify <- function(x){
    for (i in participant){ 
    if (x[i] > 12) 
        (x[i]=x[i]-12)
        print (x[i])
}}
Run Code Online (Sandbox Code Playgroud)

当我将该函数作为modify(参与者)运行时,它运行正常,但向量参与者的元素保持不变.

有什么建议,我哪里出错了?

Rol*_*and 5

不要使用循环.

participant <- participant - (participant > 12) * 12 
Run Code Online (Sandbox Code Playgroud)

如果你坚持使用你的函数,循环索引,让你函数返回修改后的向量并分配它:

modify <- function(x){
    for (i in seq_along(participant)){ 
      if (x[i] > 12) x[i]=x[i]-12
    } 
  return(x)
}

participant <- modify(participant)
Run Code Online (Sandbox Code Playgroud)

当然,循环更难写,也更慢.