# Pesudocode ----> R code

Given the array T = [1, 2, 3, 4, 5, 6], the following pseudocode

``````n <- length(T)

for i <- 2 to n step 2 do

T[i] <- T[i-1]

end for

return(T)
``````

results in:

T = [1, 1, 3, 3, 5, 5]

My goal is to transform the pseudocode to R code:

my code:

``````T = c(1,2,3,4,5,6)
n=length(T)

i=2
for (i in T ,by=2) {
T[i] = T[i-1]
end
}
return(T)
``````

further help is appreciated.
thanks

It might be helpful for you to know how to properly format code and console output that you post here. Using proper code formatting makes the site easier to read, prevents confusion (unformatted code can get garbled by the forum software ), and is generally considered the polite thing to do. Check out this FAQ to find out how â€” it's as easy as the click of a button! :

2 Likes

in that case, `i` will literally takes the values in `T`. From the looks of it, you want `i` to be an integer, so you need to define that sequence separately: `for(i in 1:T)` for example.

Also,

R does not have a `by` option in `for()`. So that means you need to modify directly the `1:n` to make it have the index you want.

this is not required in R, but implied by the `}`.

`return()` is only meaningful within a function.

this one doesn't work, as the value of `i` gets redefined when you write `for ( i in ...`. So you really need to define first the vector of indices you want to loop on, then start the loop.

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.