How to write a result of function in the global environment in R

南楼画角 提交于 2019-12-24 02:16:43

问题


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.


回答1:


Instead of lapply(D,s), use:

D <- lapply(D, s)
names(D) <- c("A", "B", "C")
list2env(D, envir = .GlobalEnv)



回答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


来源:https://stackoverflow.com/questions/44359348/how-to-write-a-result-of-function-in-the-global-environment-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!