analytics3345
analytics3345

Reputation: 65

storing results of a for function in list or

add <- c( 2,3,4)

for (i in add){
  a <- i +3
  b <- a + 3
  z <- a + b
  print(z)

}

# Result
        [1] 13
        [1] 15
        [1] 17

In R, it can print the result, but I want to save the results for further computation in a vector, data frame or list

Thanks in advance

Upvotes: 1

Views: 72

Answers (4)

David Arenburg
David Arenburg

Reputation: 92282

This is simple algebra, no need in a for loop at all

res <- (add + 3)*2 + 3 
res
## [1] 13 15 17

Or if you want a data.frame

data.frame(a = add + 3, b = add + 6, c = (add + 3)*2 + 3)
#   a  b  c
# 1 5  8 13
# 2 6  9 15
# 3 7 10 17

Though in general, when you are trying to something like that, it is better to create a function, for example

myfunc <- function(x) {
  a <- x + 3
  b <- a + 3
  z <- a + b
  z
}

myfunc(add)
## [1] 13 15 17

In cases when a loop is actually needed (unlike in your example) and you want to store its results, it is better to use *apply family for such tasks. For example, use lapply if you want a list back

res <- lapply(add, myfunc)
res
# [[1]]
# [1] 13
# 
# [[2]]
# [1] 15
# 
# [[3]]
# [1] 17

Or use sapply if you want a vector back

res <- sapply(add, myfunc)
res
## [1] 13 15 17

Upvotes: 2

IRTFM
IRTFM

Reputation: 263301

It might be instructive to compare these two results with those of @dugar:

> sapply(add, function(x) c(a=x+3, b=a+3, z=a+b) )
  [,1] [,2] [,3]
a    5    6    7
b   10   10   10
z   17   17   17

That is the result of lazy evaluation and sometimes trips us up when computing with intermediate values. This next one should give a slightly more expected result:

> sapply(add, function(x) c(a=x+3, b=(x+3)+3, z=(x+3)+((x+3)+3)) )
  [,1] [,2] [,3]
a    5    6    7
b    8    9   10
z   13   15   17

Those results are the transpose of @dugar. Using sapply or lapply often saves you the effort off setting up a zeroth case object and then incrementing counters.

> lapply(add, function(x) c(a=x+3, b=(x+3)+3, z=(x+3)+((x+3)+3)) )
[[1]]
 a  b  z 
 5  8 13 

[[2]]
 a  b  z 
 6  9 15 

[[3]]
 a  b  z 
 7 10 17 

Upvotes: 0

Josh W.
Josh W.

Reputation: 1123

Try something like:

add <- c(2, 3, 4)

z <- rep(0, length(add))

idx = 1
for(i in add) {
    a <- i + 3
    b <- a + 3
    z[idx] <- a + b
    idx <- idx + 1
}

print(z)

Upvotes: 2

dugar
dugar

Reputation: 324

For a data.frame to keep all the info

add <- c( 2,3,4)

results <- data.frame()

for (i in add){
  a <- i +3
  b <- a + 3
  z <- a + b
  #print(z)
  results <- rbind(results, cbind(a,b,z))
}
 results
  a  b  z
1 5  8 13
2 6  9 15
3 7 10 17

If you just want z then use a vector, no need for lists

add <- c( 2,3,4)

results <- vector()

for (i in add){
  a <- i +3
  b <- a + 3
  z <- a + b
  #print(z)
  results <- c(results, z)
}

results
[1] 13 15 17

Upvotes: 1

Related Questions