arrays - Looping through a Vector -
i using rstudio , trying create function loop through vector , perform calculation while condition. function should return data frame entered vector in 1 column , number of iterations took satisfy while condition in another. have created function preformed calculation while condition serves basic operation function having problems with. here is:
t5<-function(x){ z=x while(x != 1){ if(x %% 2 == 0) x= x/2 else x= (3 * x +1) z=c(z, x) } return (z) }
here have new function...my problem function (t7):
t7<-function(x){ y=0 i=0 for(i in 1:length(x)){ y[i]=length(t5(x[i]))-1 print(y[i]) } #m<-data.frame(x, y[i]) }
i had print y[i] because way function something. here output shows (which half of need):
t7(2:10) [1] 1 [1] 7 [1] 2 [1] 5 [1] 8 [1] 16 [1] 3 [1] 19 [1] 6
can me understand how make t7(2:10) run through array , return data frame listing array , number of iterations took reach number 1 each number in array? appreciated.
you can obtain vector need sapply
function:
data.frame(x=2:10, iters=sapply(2:10, function(x) length(t5(x))-1)) # x iters # 1 2 1 # 2 3 7 # 3 4 2 # 4 5 5 # 5 6 8 # 6 7 16 # 7 8 3 # 8 9 19 # 9 10 6
Comments
Post a Comment