是否有R函数用于导出数据表中的列表和子列表名称? 更新数据

问题描述

我从函数中得到以下输出

DataSet$DataSet01$`1`$`1`
[1] 0.016082

DataSet$DataSet01$`1`$`2`
[1] 0.025863

DataSet$DataSet01$`1`$`3`
[1] 0.036965

我想创建一个包含两列的数据表,一列是ID,另一列是输出

ID                         Var1
DataSet$DataSet01$`1`$`1`  0.016082
DataSet$DataSet01$`1`$`2`  0.025863
DataSet$DataSet01$`1`$`3`  0.036965

示例

DT <- data.table (A=c(1,1,2,3,4,5),B=c(200,210,300,420,289,365,587,250,110,500,800),C=c(0.6,0.35,0.6,0.85,0.22,0.36,0.39,0.31,0.33,0.58,0.66))
DT
DT_Split <- split(DT,DT$A)
names(DT_Split) <- c(paste("FF",names(DT_Split),sep = ""))
list2env(DT_Split,.GlobalEnv)
lapply(DT_Split,function(x){
  x[,NewColumn := cumsum(c(TRUE,diff(B) < 0))]})
DT_Split2 <- lapply(DT_Split,function(x) split(x,x$NewColumn))

REREG<-lapply(DT_Split2,function(x) {lapply(x,function(x) {summary(lm(formula=B~C,data=x))})})

REREG_R2<-lapply(REREG,function(x){lapply(x,function(x){
      x$r.squared})})

REREG_R2的输出为:

$FF1
$FF1$`1`
[1] 0.1758242


$FF2
$FF2$`1`
[1] 0

$FF2$`2`
[1] 0


$FF3
$FF3$`1`
[1] 1


$FF4
$FF4$`1`
[1] 0

$FF4$`2`
[1] 1


$FF5
$FF5$`1`
[1] 0

我可以为变量创建数据表,但是无法提取添加ID。 我感谢任何可以帮助我做到这一点的代码

预先感谢, 米拉德(Milad)

解决方法

我们可以在stack中使用base R

stack(lstout)[2:1]
#                      ind   values
#1 DataSet$DataSet01$`1`$`1` 0.016082
#2 DataSet$DataSet01$`1`$`2` 0.025863
#3 DataSet$DataSet01$`1`$`3` 0.036965

或使用enframe

library(dplyr)
library(tibble)
library(tidyr)  
enframe(lstout) %>% 
     unnest(c(value))
# A tibble: 3 x 2
#  name                       value
#  <chr>                      <dbl>
#1 DataSet$DataSet01$`1`$`1` 0.0161
#2 DataSet$DataSet01$`1`$`2` 0.0259
#3 DataSet$DataSet01$`1`$`3` 0.0370

更新

如果数据是高度嵌套的,请使用rrapply

library(rrapply)
library(dplyr)
library(tidyr)
library(stringr)
rrapply(DataSet,how = "melt") %>% 
       unite(ID,L1,L2,L3,sep = '$') %>%
       mutate(ID = str_c('DataSet$',ID)) %>%
       rename(Var1 = value)
#                   ID     Var1
#1 DataSet$DataSet01$1$1 0.016082
#2 DataSet$DataSet01$1$2 0.025863
#3 DataSet$DataSet01$1$3 0.036965
#4 DataSet$DataSet02$1$1 0.016082
#5 DataSet$DataSet02$1$2 0.025863
#6 DataSet$DataSet02$1$3 0.036965

或使用rapply中的base R

stack(rapply(REREG_R2,as.data.frame))[2:1]

数据

lstout <- list("DataSet$DataSet01$`1`$`1`" = 0.016082,"DataSet$DataSet01$`1`$`2`" = 0.025863,"DataSet$DataSet01$`1`$`3`" = 0.036965)

DataSet <- list(DataSet01 = list(`1` = list(`1` = 0.016082,`2` = 0.025863,`3` = 0.036965)),DataSet02 = list(`1` = list(`1` = 0.016082,`3` = 0.036965)))