为什么这个列表不能作为元素存储在数据框中?

Why this list can't be stored as element in data frame?

我 运行 一个 randomforest 模型并尝试将模型作为元素存储在数据框中。我通常用 list() 包裹起来并将其存储为一个元素,但这里似乎我需要两层 list(list())。有人可以解释为什么,并告诉我 list(list()) 是否是解决此问题的好方法?

library(randomForest)

data1 = data.frame(A = sample.int(100, size = 100))
data1$B = data1$A
data1$C = data1$A
data1$D = data1$A

report = data.frame(ntree = 500, mtry = 1:3, model = NA)

for ( i_row in 1:nrow(report)){

        ntree = report[i_row, 'ntree']
        mtry = report[i_row, 'mtry']

        rf = randomForest( D ~ ., data = data1, importance = T, ntree = ntree, mtry = mtry)

        report[i_row, 'model'] = rf  # not work
        report[i_row, 'model'] = list(rf)  # not work
        report[i_row, 'model'] = list(list(rf))  # works
}

数据框在内部是列表,如果您考虑 str(rf),您会发现 randomForest-model 在内部也表示为列表。但是属性有不同的维度,所以 rf 不能转换为 data.frame

R 尽最大努力以某种合理的方式将列表或列表的列表转换为 data.frame。考虑

a <- data.frame(x=c(1,2),y=c(1,2))

在作业中

a[2,] <- list(x=3, y=3)

右侧列表被解释为分配给 a 的第二行的行。

赋值 a[2,] <- list(list(x=3, y=3)) 失败,因为右侧不能解释为一行,但可以强制转换为一列:

a[,1] <- list(list(x=3, y=3))

这导致

  x y
1 3 1
2 3 2

最后,本例中的list(list(...))"trick"是:

a[2,] <- list(list(list(x=3, y=3)))
> a
     x    y
1    1    1
2 3, 3 3, 3

现在 R 放弃了将右侧对象强制转换为行和列,并接受它作为列表的包装列表。这与您所做的大致相同。

所以至少它可以重现。但这是个好主意吗?我会否认。

Dataframes 用于表格数据,而不是用于将复杂对象包装到列表列表中。