【问题标题】:Apply common function to all data frames and return data frames with same name将通用函数应用于所有数据帧并返回具有相同名称的数据帧
【发布时间】:2017-01-24 01:35:02
【问题描述】:

我正在尝试将一个函数应用于我在 R 中的全局环境中的所有类似拼写的数据帧。我想将此函数应用于所有这些数据帧,但如果没有我指定,我不知道该怎么做1 x 1。我想将数据框以与以前相同的拼写返回到全局环境。

mtcars_test = mtcars
iris_test = iris
#....etc......could be 2 of them or 88 of them...but they will all end in "_test"

# figure out what data frames I am working with
list_of_my_dfs = lapply(ls(pattern = "*_test"), get)

#my function just multiples everything by 2
mytest_function = function(df){ df = df*2; return(df)}

helpme_return_these_dfs_to_outside_the_list=plyr::llply(list_of_my_dfs, mytest_function)

这是我需要帮助的地方。我想将我的函数应用于列表中的每个数据框,然后将该列表中的数据框“返回”到我的环境中。因此mtcars_test 和所有其他数据帧将在任何地方乘以 2 并返回到全局环境。

【问题讨论】:

  • 为什么不把所有东西都放在一个列表中呢?
  • 我可以将它保存在一个列表中,但我现在的目的是我需要将它们提取出来。我已经知道如何做到这一点,并且认为我现在正在这样做。
  • “答案”可能是list2env,但请不要为此烦恼。只需将它们列在一个列表中即可。

标签: r list plyr lapply


【解决方案1】:

您可以使用eapply 迭代一个环境,然后使用assign 将一个对象存储到您的全局环境中。 eapply 的函数参数将是一个匿名函数,它首先从全局获取 df,将其分配给临时变量,将其传递给您的函数,然后使用 assign 将其放回全局。

【讨论】:

  • 你能举个例子吗?我以前从未听说过这个功能。
  • 阅读帮助文件!你想做的是进阶,阅读危险,所以你真的需要花时间学习你在做什么。
【解决方案2】:

1) 环境下标e 设置为包含数据帧的环境,然后获取它们的名称并循环它们,如下所示:

BOD_test <- BOD  # not all columns of iris are numeric so use BOD instead
mtcars_test <- mtcars

e <- .GlobalEnv
nms <- ls(pattern = "_test$", envir = e)
for(nm in nms) e[[nm]] <- mytest_function(e[[nm]])

1a) assign 最后一条语句的替代方案是:

for(nm in nms) assign(nm, mytest_function( get(nm, e) ), e)

2) 列表您可能希望将数据框保留在列表中:

L <- sapply(nms, get, envir = e, simplify = FALSE)
L[] <- lapply(L, mytest_function)

2a) sapply 或者如果您不想覆盖L,则:

sapply(L, mytest_function, simplify = FALSE)

【讨论】:

    猜你喜欢
    • 2017-12-05
    • 1970-01-01
    • 2019-03-05
    • 2019-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    相关资源
    最近更新 更多