简体   繁体   中英

write an for loop function in R

I would like to write a simple function that loops through a vector and adds one to each value. How should I go about it?

x<-1:10
x_plus_one<-function(i){
  for (i in x)
    i+1}

This function does not return anything.

What is expected should be sthg like below:

> x1<-x+1
> x1
 [1]  2  3  4  5  6  7  8  9 10 11 

thanks @Allan Cameron

func <- function(x) 
{ for(i in seq_along(x)) 
    x[i] <- x[i] + 1; 
return(x)
}
x<-(5:10)
> func(x)
[1]  6  7  8  9 10 11

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM