【问题标题】:environment issue环境问题
【发布时间】:2022-01-18 11:45:34
【问题描述】:
e <<- data.env ## here i am storing my rdata
data_frames <- Filter(function(x) is.data.frame(get(x)), ls(envir = e)) ## getting only dataframe
for(i in data_frames) e[[i]] <<- mytest_function(e[[i]]) ###  here i am iterating the dataframe 

现在,如何将 for 循环转换为 apply 函数?循环需要很长时间才能迭代。

【问题讨论】:

  • 您要求优化代码,但您的问题不可重现。它缺少1. 可重现格式的样本数据、2. 您现在使用的代码(mytest_function() 是什么样的?)和3. 所需的输出。如果没有这三个项目,我怀疑你会得到好的答案(如果有的话)。
  • 我同意大多数时候都需要可重复的数据,但这显然是一个基本问题,任何 df 都可以做,任何函数都可以做。只是关于如何正确使用 lapply 循环遍历 data.frames 并在其中任何一个上调用函数的一些基本解释。

标签: r for-loop sapply


【解决方案1】:
好的,这里一些基本演示和我认为这是一个很好的用途申请,特别是因为循环中的环境问题和这样。
# lets create some data.frames
df1 <- data.frame(x = LETTERS[1:3], y = rep(1:3))
df2 <- data.frame(x = LETTERS[4:6], y = rep(4:6))

# what df's are we going to "loop" over
data_frames <- c("df1", "df2")

# just some simple function to paste x and y from your df's to a new column z
mytest_function <- function(x) {
  df <- get(x)
  df$z <- paste(df$x, df$y)
  df
}

# apply over your df's and call your function for every df
e <- lapply(data_frames, mytest_function)

# note that e will be a list with data.frames
e

[[1]]
  x y   z
1 A 1 A 1
2 B 2 B 2
3 C 3 C 3

[[2]]
  x y   z
1 D 4 D 4
2 E 5 E 5
3 F 6 F 6

# most of the time you want them combined
e <- do.call(rbind, e)

e
  x y   z
1 A 1 A 1
2 B 2 B 2
3 C 3 C 3
4 D 4 D 4
5 E 5 E 5
6 F 6 F 6

【讨论】:

    【解决方案2】:

    不清楚您想要的结果是什么。但是,如果您只想对数据框中的每一列应用一个函数,那么您可以使用sapply

    sapply(df, function(x) mytest_function(x))
    

    或者您可以使用purrr 包。

    purrr::map(df, function(x) mytest_function(x)) %>% 
       as.data.frame
    

    如果您有一个数据框列表并且正在对每个数据框应用一个函数,那么您也可以使用purrr

    library(purrr)
    
    purrr::map(data_frames, mytest_function)
    

    【讨论】:

    • 非常感谢 Andrew 申请和 purr 工作正常
    • 出于兴趣 - 为什么 purrr 而不是为第二部分应用函数?
    • @GeorgeSavva 这真的只是偏好。一般来说,我只是更喜欢尽可能使用tidyversepurrr 是其中的一部分)。
    【解决方案3】:

    当您想将循环转换为应用函数时,我通常会选择 lapply 但这取决于具体情况:

    my_f <- function(x) {
    mytest_function(e[[x]])
    }
    my_var <- lapply(1:length(data_frames), my_f)
    

    【讨论】:

      猜你喜欢
      • 2019-05-29
      • 1970-01-01
      • 2016-01-22
      • 2023-03-27
      • 1970-01-01
      • 2019-04-09
      • 2011-04-04
      • 2015-10-16
      • 2021-07-22
      相关资源
      最近更新 更多