Reputation: 158
I am new to R. There is plenty on here and the rest of the web around writing functions to return the Collatz conjecture for a given integer.
As such, i have managed to create a function that will:
numseq <- function(num)
{
if(num == 1)
return(NULL)
if(num %% 2 == 0)
return(num / 2)
return(3 * num + 1)
}
seqfetch <- function(input)
{
result <- input
while(input != 1)
{
input <- numseq(input)
result <- c(result, input)
}
return(result)
}
seqfetch(15)
However i have a vector nums<-1:30
and am trying to loop through each element of it and run the function against it, outputting the values for each iteration and each value of n.
I am aiming for:
n = 2: [1] 2 1
n = 3: [1] 3 10 5 16 8 4 2 1
...
...
...
n = 30: [1] 30 15 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
And so on...
I dont know a lot about R and have tried wrapping the whole thing in a loop. I have also tried the same thing with a matrix of one column. I get an error saying that only the first element will be used.
Can anyone help with the loop please? Or am i going about it the wrong way?
Thanks
Upvotes: 0
Views: 105
Reputation: 76683
Here is another way, rewriting numseq
as a recursive function.
numseq <- function(num) {
if(num == 1)
num
else if(num %% 2 == 0)
c(num, numseq(num / 2))
else
c(num, numseq(3 * num + 1))
}
Now all you have to do is
lapply(1:30, numseq)
Or, in the form of a function,
seqfetch2 <- function(input){
lapply(input, numseq)
}
seqfetch2(1:30)
Upvotes: 1
Reputation: 158
I managed to acheive the desired output using sapply(). By wrapping function 2 in sapply() as below:
sapply(1:30, function(input)
{
result <- input
while(input != 1)
{
input <- numseq(input)
result <- c(result, input)
}
return(result)
}
)
I acheived the desired output of:
[[1]]
[1] 1
[[2]]
[1] 2 1
[[3]]
[1] 3 10 5 16 8 4 2 1
[[4]]
[1] 4 2 1
[[5]]
[1] 5 16 8 4 2 1
[[6]]
[1] 6 3 10 5 16 8 4 2 1
[[7]]
[1] 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
[[8]]
[1] 8 4 2 1
[[9]]
[1] 9 28 14 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
And so on through to 30.
Upvotes: 0