Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

How Can I make an R for loop for summations?

Hello I'm really new to R and having trouble figuring this out, I have to make a summation and compute for different values of n

Here is the summation I'm trying to do

I have the following code

x=0:10

k=x

sum(1(k+1)^2)

which gives me the answer for the first value of N, however, do I just repeat it for all different values of N, or can I make a for loop that will go from 0:10 -> 0:20 -> 0:50 -> 0:100 Any help is appreciated

question from:https://stackoverflow.com/questions/66057036/how-can-i-make-an-r-for-loop-for-summations

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can create a list of sequences and then use sapply :

x= list(0:10, 0:20, 0:50, 0:100)

result <- sapply(x, function(k) sum(1/(k+1)^2))
result
#[1] 1.558 1.598 1.626 1.635

With a for loop :

result <- numeric(length(x))
for(i in seq_along(x)) {
  result[i] <- sum(1/(x[[i]]+1)^2)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...