gpt4 book ai didi

rapply 到 R 中数据框的嵌套列表

转载 作者:行者123 更新时间:2023-12-04 11:39:29 26 4
gpt4 key购买 nike

我有一个嵌套列表,其基本元素是数据帧,我想递归地遍历这个列表来对每个数据帧进行一些计算,最后得到一个与输入结构相同的嵌套结果列表。我知道“rapply”正是针对此类任务,但我遇到了一个问题,rapply 实际上比我想要的更深入,即它分解每个数据框并改为应用于每一列(因为数据框本身就是一个列表在 R)。

我可以考虑的一种解决方法是将每个数据帧转换为矩阵,但它会强制统一数据类型,所以我真的不喜欢它。我想知道是否有任何方法可以控制 rapply 的递归深度。任何的想法?谢谢。

最佳答案

2020 年 6 月更新 :
您现在也可以使用 rrapplyrrapply -package,(基础 rapply 的扩展版本)。设置classes = "data.frame"应用 f函数将 data.frame 对象作为一个整体(而不是递归到各个列):

library(rrapply)

L <- list(a = BOD, b = BOD)

## apply f to data.frames
rrapply(L, f = colSums, classes = "data.frame")
#> $a
#> Time demand
#> 22 89
#>
#> $b
#> Time demand
#> 22 89

## apply f to individual columns of data.frames
rrapply(L, f = function(x, .xname) if(.xname == "demand") scale(x) else x)
#> $a
#> Time demand
#> 1 1 -1.4108974
#> 2 2 -0.9789900
#> 3 3 0.8998070
#> 4 4 0.2519460
#> 5 5 0.1655645
#> 6 7 1.0725699
#>
#> $b
#> Time demand
#> 1 1 -1.4108974
#> 2 2 -0.9789900
#> 3 3 0.8998070
#> 4 4 0.2519460
#> 5 5 0.1655645
#> 6 7 1.0725699

关于rapply 到 R 中数据框的嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17971073/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com