x=c(1,2,3,4)
y=c(4,5,6,7)
example1<-function(x,y)
#start functions in curly bracket
{
#initialize the values to store squared values
n<-length(x)
x1<-0
y1<-0
z1<-0
{#then start iterations
for(i in 1:n)
x1[i]<-x[i]^2
y1[i]<-y[i]^2
z1[i]<-(x[i]/y[i])^2
#close with curly bracket}
sumx1<-sum(x1)
sumy1<-sum(y1)
sumz1<-sum(z1)
g<- sumx1/ sumy1
h<- sumz1
cat("The values are",g,"and",h,"\n")
}
example1(x,y)
many functions in r are vectorized, it means you don't need loops for iteration
x=c(1,2,3,4)
y=c(4,5,6,7)
cat("The values are", sum(x^2)/sum(y^2),"and", sum((x/y)^2),"\n")
#The values are 0.2380952 and 0.7990306
Ok that makes sense; but what if I want to write a program that includes the iterations?
Thanks for the solution. It is correct but I wanted to use the iterations commands to practice loops.
"Of course someone has to write loops. It doesn’t have to be you." @JennyBryan
for (i in x) {f} means for each element in x do the f
for (i in seq_along(x)) {f} means for each index of x do the f
in your case, I would create the following function
example<-function(x,y){
sum_of_squares1<-0
sum_of_squares2<-0
sum_of_squaresof_ratio<-0
for (i in x){
sum_of_squares1<-sum_of_squares1+i^2
}
for (i in y){
sum_of_squares2<-sum_of_squares2+i^2
}
if(length(x)!=length(y)) stop("vectors are not the same lentgh")
for (i in seq_along(x)){
sum_of_squaresof_ratio <- sum_of_squaresof_ratio+(x[i]/y[i])^2
}
cat("The values are", sum_of_squares1/sum_of_squares2,"and", sum_of_squaresof_ratio,"\n")
the curly bracket occurs after the for condition. and you ommitted the closing one, by commenting it out ...
z1<-0
#then start iterations
for(i in 1:n) {
x1[i]<-x[i]^2
y1[i]<-y[i]^2
z1[i]<-(x[i]/y[i])^2
} #close with curly bracket
thanks melih; the code misses a ' curly bracket' at the end. This code was a trial in my learning curve. Million miles to go!!!
Could you please tell me where I have made mistakes in my code, so that I can learn from them. As I try to execute my code, it throws up an error that the values are NA and NA.
If you are asking it seems you didnt understand the words in my post to you.
So here is a full edit version of your code, with the corrections I suggested to you.
x=c(1,2,3,4)
y=c(4,5,6,7)
example1<-function(x,y)
#start functions in curly bracket
{
#initialize the values to store squared values
n<-length(x)
x1<-0
y1<-0
z1<-0
#then start iterations
for(i in 1:n)
{
x1[i]<-x[i]^2
y1[i]<-y[i]^2
z1[i]<-(x[i]/y[i])^2
}
#close with curly bracket
sumx1<-sum(x1)
sumy1<-sum(y1)
sumz1<-sum(z1)
g<- sumx1/ sumy1
h<- sumz1
cat("The values are",g,"and",h,"\n")
}
example1(x,y)
Thanks Nir, I made mistakes in running the for loop.
This topic was automatically closed 7 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.