r - 使用函数从不同级别的列表中提取数据

标签 r list dataframe extract hierarchy

大家早上好。

我有一个函数,它使用列表作为参数,通过将元素提取到 df 中来生成不同的指标。但是,我打算使用的列表具有不同的层次结构级别,因此我无法在所有列表上使用它。

我在下面给出一个例子(不是真正的函数):

# the function pulls out a df from a list
df_func <- function(list){
  
  df_temp <- list[[1]]
  
  return(df_temp)  
  
}

data("iris") 

list_a <- list("list_a" = iris, "list_b" = iris,
                     "list_c" = iris, "list_d" = iris)

list_b <- list()
list_b[["list_a"]] <- list_a
list_b[["list_b"]] <- list_a
list_b[["list_c"]] <- list_a
list_b[["list_d"]] <- list_a

df1 <- df_func(list_a) # correct (returns a df)
df2 <- df_func(list_b) # wrong (returns a list of dfs)

我知道问题在于,要从 list_a 访问正确的元素,我们使用 list_a[[1]] 来从中提取正确的元素list_b 我们必须使用list_b[[1]][[1]]

我的问题是如何在函数中对此进行编码,以便 R 知道在哪里查找我需要的 df?

感谢大家对新手的帮助。

最佳答案

考虑使用已经可用的递归函数,即rapply/rrapply

df_func <- function(listObj) {
     rrapply::rrapply(listObj, classes = "data.frame", how = 'flatten')[[1]]
   }

-测试

> out1 <- df_func(list_a)
> out2 <- df_func(list_b)
> str(out1)
'data.frame':   150 obs. of  5 variables:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
> str(out2)
'data.frame':   150 obs. of  5 variables:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

关于r - 使用函数从不同级别的列表中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68417662/

相关文章:

python - 不平等加入 Pandas ?

r - 将 .numbers 电子表格导入 R

r - facet_wrap 中因子级别的顺序

r - 根据特定行的条件创建一个新变量

c# - 如何轻松初始化元组列表?

python - 遍历元组列表包含python中的字符串和列表

r - 查找与值关联的子组并计算每个 ID 中的连续子组

python - 按字符拆分列表中的元素

python:分离出 Pandas 数据框中有重复项的行

r - 多个数据框中的多个相同列 - R