4

I have these datasets: A <- 4, B <- 3, C <- 2.

So I put them in a list D<-list(A,B,C) and want to apply this function:

s<-function(x) {
    t<-8
    x<-as.data.frame(x*t)
}

lapply(D,s)

when I apply the lapply function it just print them.

How can I make it saving the result in the global environment instead of printing them?

So the result should be A with value of 32 B with value of 24 C with value of 16.

J-Alex
  • 6,881
  • 10
  • 46
  • 64
Kingindanord
  • 1,754
  • 2
  • 19
  • 48
  • It sounds like you want the [`scoping assignment arrow`](https://stackoverflow.com/q/2628621/5977215) – SymbolixAU Jun 04 '17 at 22:39
  • I tried it at this point `x<<-as.data.frame(x*t)` the problem that it writes the value with name `x` instead of `A, B , C` – Kingindanord Jun 04 '17 at 22:42
  • 1
    Would it be OK for you to store the result of `lapply` in the existing variable `D` ("overwrite it"). The single variables A, B and C will not be changed by this but using single variables without a "container" like a list makes it really difficult to apply flexible algorithms... You can access the variables then via `D$A`, `D$B` and `"D$C` which is only kinda namespace (consider it as a "full qualified variable name"). – R Yoda Jun 04 '17 at 22:59

2 Answers2

9

Instead of lapply(D,s), use:

D <- lapply(D, s)
names(D) <- c("A", "B", "C")
list2env(D, envir = .GlobalEnv)
Leandro Mineti
  • 196
  • 1
  • 1
  • 8
  • Well done, +1 (I didn't know that `list2env` replaces existing variables without a warning) – R Yoda Jun 04 '17 at 23:14
2

It is better to store all your variables "straying" in the global environment in a list (keeps the environment clean/smaller and allows every kind of looping):

D <- list(A = 4, B = 3, C = 2)

s <- function(x) {
  t <- 8
  x * t   # return just the value
}

result <- lapply(D, s)
names(result) <- names(D)  # rename the results
D <- result  # replace the original values with the "updated" ones

D
D$A  # to access one element
R Yoda
  • 8,358
  • 2
  • 50
  • 87
  • I am trying to change the values in the global environment. so a data set that called `A` should be changed to `A*t`. so after applying the function I should not see the old `A <- 4` it must be the new `A<-32` and it should be separated from the `B` and `C`... maybe I misunderstood the use of `lapply`. – Kingindanord Jun 04 '17 at 22:37
  • OK, now I understand the goal of your question. R always passes function parameter "by value" so that you can change them only locally (within the function) but variable of the caller will **not** change. This behavior is independent of `lapply`. I continue asking using comments on your question now... – R Yoda Jun 04 '17 at 22:54