简体   繁体   English

使用lapply函数创建新的聚合R数据帧

[英]Creating new aggregated R dataframes with a function in lapply

I want to create new aggregated dataframes from existing ones that are collected in a list. 我想从列表中收集的现有数据框架中创建新的聚合数据框架。 Ideally they would appear as their own dataframes indicated by a prefix. 理想情况下,它们将显示为由前缀指示的自己的数据帧。 This is where I've got: 这是我得到的地方:

dfList <- list(A = data.frame(y = sample(1:100), x = c("grp1","grp2")),
               B = data.frame(y = sample(1:100), x = c("grp1","grp2")))

agrFun <- function(df){
    prefix <- deparse(substitute(df))
    assign(paste0(prefix,"_AGR"),
           aggregate(y ~ x, data = df, sum))
}

lapply(seq_along(dfList), function(x) agrFun(dfList[[x]]))

Aggregation happens as intended but I'm not sure what I need to do otherwise in order to create dataframes A_AGR and B_AGR. 聚合按预期发生,但我不确定为了创建数据帧A_AGR和B_AGR我还需要做什么。

EDIT: A bit of clarification. 编辑:一点澄清。 I want to have the aggregated dataframes appear in the environment. 我希望聚合的数据框出现在环境中。

So instead of this 所以不要这样

ls() [1] "agrFun" "dfList" ls()[1]“agrFun”“dfList”

my goal is to have 我的目标是拥有

ls() [1] "A_AGR" "B_AGR" "agrFun" "dfList" ls()[1]“A_AGR”“B_AGR”“agrFun”“dfList”

EDIT2: EDIT2:

Or more ideal would be to have dfList include dataframes A, A_AGR, B and B_AGR after the process. 或者更理想的是让dfList包括进程后的数据帧A,A_AGR,B和B_AGR。

EDIT3: EDIT3:

And I also want to preserve the names of the dataframes. 我还想保留数据帧的名称。

Your way to do seems extremely complicated. 你的方式似乎非常复杂。 You can create the wanted named data.frames in a list with this one liner: 您可以使用以下data.frameslist创建所需的命名data.frames

setNames(lapply(dfList, function(u) aggregate(y~x, u, sum)), paste0(names(dfList),"_AGR"))

#$A_AGR
#     x    y
#1 grp1 2340
#2 grp2 2710

#$B_AGR
#     x    y
#1 grp1 2573
#2 grp2 2477

With your function agrFun : 使用你的函数agrFun

lst = setNames(lapply(dfList, function(x) agrFun(x)), paste0(names(dfList),"_AGR"))

If you want to append the two lists: 如果要附加两个列表:

dfList = append(lst, dfList)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM