如何在 R 的全局环境中编写函数的结果

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

我有这些数据集:A <- 4, B <- 3, C <- 2

所以我把它们放在一个列表中 D<-list(A,B,C) 并想应用此功能:

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

lapply(D,s)

当我应用 lapply 函数时,它只是打印它们。

如何让它在全局环境中保存结果而不是打印它们?

所以结果应该是 A 值为 32 B 值为 24 C 值为 16.

最好将所有变量 "straying" 存储在 list 的全局环境中(保持环境 clean/smaller 并允许各种循环):

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

代替lapply(D,s),使用:

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