antekkalafior
antekkalafior

Reputation: 282

How to add function result to a list

I'm trying to add result of my function to an empty list. I've seen many questions about it but i can't figure out how to implement them in my code

a1 <- runif(10, 0, 1)
a2 <- runif(15, 0, 1)
a3 <- runif(20, 0, 1)
a4 <- runif(25, 0, 1)
a5 <- runif(30, 0, 1)
a6 <- runif(35, 0, 1)
a7 <- runif(40, 0, 1)
a8 <- runif(45, 0, 1)
a9 <- runif(50, 0, 1)
a10 <- runif(55, 0, 1)
a11 <- runif(60, 0, 1)
a12 <- runif(65, 0, 1)

dane <- list()
Estymator_sredniej <- function(która_próba, liczebnosc) {
  res <- round((1/liczebnosc) * sum(która_próba), digits = 3)
  cat(paste(res),sep = "\n")
  new_element <- res
  dane[[length(dane) + 1]] <- new_element
}

lista <- list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12)
o <- 10
for (i in lista){
  Estymator_sredniej(i, o)
  o <- o + 5
}

I'm trying to add "res" which is a normal number for example 0.385 to a list named "dane"

The list ends up empty every time i try to run the code.

for debugging i printed res (it works)

I tried using this

 new_element <- 5
 dane[[length(dane) + 1]] <- new_element

to add 5 to my list (it works)

So why i can't add res to this list? I am honestly out od ideas

Upvotes: 0

Views: 45

Answers (1)

ThomasIsCoding
ThomasIsCoding

Reputation: 101343

I guess you need <<- within your function Estymator_sredniej, e.g.,

dane <- list()
Estymator_sredniej <- function(która_próba, liczebnosc) {
  res <- round((1 / liczebnosc) * sum(która_próba), digits = 3)
  dane[[length(dane) + 1]] <<- res
}

lista <- list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12)
o <- 10
for (i in lista) {
  Estymator_sredniej(i, o)
  o <- o + 5
}

such that

> dane
[[1]]
[1] 0.502

[[2]]
[1] 0.482

[[3]]
[1] 0.544

[[4]]
[1] 0.498

[[5]]
[1] 0.532

[[6]]
[1] 0.473

[[7]]
[1] 0.517

[[8]]
[1] 0.499

[[9]]
[1] 0.472

[[10]]
[1] 0.462

[[11]]
[1] 0.508

[[12]]
[1] 0.484

Upvotes: 0

Related Questions