Kdot
Kdot

Reputation: 13

Sum up a vector

Here's my attempt with a for loop

for(j in seq(from=1, to=5, by=1)){
p2 <- sum(j, na.rm = FALSE)
print(p2)
}

I'm getting this as output:

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

but I need the sum of these variables, this equals 15.

Upvotes: 0

Views: 80

Answers (4)

Ricky
Ricky

Reputation: 4686

Don't really understand "but I need the sum of these variables". Are you looking for cumsum(1:5) ?

> cumsum(1:5)
[1]  1  3  6 10 15

Upvotes: 0

Jthorpe
Jthorpe

Reputation: 10167

A slightly more abstract answer is (in case p2 in the problem statement is just representative of some value being calculated in a for loop):

runningTotal <- 0
for(j in seq(from=1, to=5, by=1)){
    p2 <- j # a trivial example of a value in a for loop
    runningTotal <- runningTotal + p2
}

Upvotes: 0

Scott C Wilson
Scott C Wilson

Reputation: 20016

Don't do it this way. The R way is

# Assumption:
j <- c(1,2,3,4,5)   # or j <- 1:5 
p2 <- sum(j)

Upvotes: 5

Stedy
Stedy

Reputation: 7469

I would suggest summing over a range to achieve the desired result:

R> for(j in seq(from=1, to=5, by=1)){ 
+   p2 <- sum(1:j, na.rm = FALSE) 
+   print(p2)
+ }
[1] 1
[1] 3
[1] 6
[1] 10
[1] 15

Upvotes: 1

Related Questions