I have a data like this
df <- seq(5,10)
I pick the first number
t <- df[1]
I want to do the following (Collatz sequence):
- if it is odd then multiple by 3 and +1
- if the answer is even divide by 2 otherwise multiply by 2
- and keep doing this until the answer is 1
Examples:
- 5 is odd then I multiple by 3 +1 will become 16 and 16 is even then I divide by 2 because 8 and 8 is even I divide by 2 become 4 and I divide by 2 become 2 and I divide by 2 become 1. Finished. Move on to the next number.
- I pick 6, it is even I divide by 2 which become 3 then I multiple by 3 +1 which becomes 10...
I have done this but I don't know how to get it together
if( (df[1]%%2) == 0) {
mydf <- df[1]* 3+1
} else {
mydf <- df[1]/2
I found that this does the job for each number at the time
mydf <- NULL
n <- 5
while (n != 1) {
if (n %% 2 == 0) {
n <- n / 2
} else {
n <- (n * 3) + 1
}
mydf <- c(mydf, cbind(n))
}
I should always give one number at the time, how can I make it to get numbers one after the other and save the intermediate results as rows?