r - 将数据框转换为 R 中列表的最快方法

标签 r

我经常需要将数据框转换为列表列表。关键之一是我需要保留类型(即:数字仍然是数字,字符串仍然是字符串)。这是我目前使用的功能:

dataframe_to_lists <- function(df){
  return_list <- lapply(split(df, 1:nrow(df)), function(row) as.list(row))
  return(return_list)
}

这是准确的,但当行数变大(> 10K)时,速度并不快。在 R 中执行此操作的最快方法是什么?

下面是一个例子:
> example_df <- data.frame(col1 = c('a', 'b', 'c'), col2 = c(1, 2, 3), col3 = c(4, 5, 6), stringsAsFactors = FALSE)
> list_result <- dataframe_to_lists(example_df)
> list_result
$`1`
$`1`$col1
[1] "a"
$`1`$col2
[1] 1
$`1`$col3
[1] 4

$`2`
$`2`$col1
[1] "b"
$`2`$col2
[1] 2
$`2`$col3
[1] 5

$`3`
$`3`$col1
[1] "c"
$`3`$col2
[1] 3
$`3`$col3
[1] 6

最佳答案

尝试:

lis <- rapply(df,as.list,how="list")
lis2 <- lapply(1:length(lis[[1]]), function(i) lapply(lis, "[[", i))

@A.Webb 提供了一个更简单快捷的解决方案:
do.call(function(...) Map(list,...),df)

例子:
set.seed(1)
df <- data.frame(col1 = letters[1:10], col2 = 1:10, col3 = rnorm(1:10))

df
   col1 col2       col3
1     a    1 -0.6264538
2     b    2  0.1836433
3     c    3 -0.8356286
4     d    4  1.5952808
5     e    5  0.3295078
6     f    6 -0.8204684
7     g    7  0.4874291
8     h    8  0.7383247
9     i    9  0.5757814
10    j   10 -0.3053884

lis <- rapply(df,as.list,how="list")
lis2 <- lapply(1:length(lis[[1]]), function(i) lapply(lis, "[[", i))

head(lis2, 2)

[[1]]
[[1]]$col1
[1] a
Levels: a b c d e f g h i j

[[1]]$col2
[1] 1

[[1]]$col3
[1] -0.6264538


[[2]]
[[2]]$col1
[1] b
Levels: a b c d e f g h i j

[[2]]$col2
[1] 2

[[2]]$col3
[1] 0.1836433

基准:
set.seed(123)
N <- 100000
df <- data.frame(col1 = rep("A", N), col2 = 1:N, col3 = rnorm(N)) 

system.time({
    lis <- rapply(df,as.list,how="list")
    lis2 <- lapply(1:length(lis[[1]]), function(i) lapply(lis, "[[", i))
})

user  system elapsed 
1.36    0.00    1.36

system.time(do.call(function(...) Map(list,...),df))

user  system elapsed 
0.69    0.00    0.69

关于r - 将数据框转换为 R 中列表的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35707732/

相关文章:

jquery - 关闭 R 中特定的 modalDialog Shiny

r - 用于 R 的堆栈函数(光栅库)的参数

r - 如何在 R 中用数字向量表示多项式

python - Rpy2 在安装时找不到我的 R 库

r - R : `[.data.frame` (m. 数据中的错误,处理):选择了未定义的列 - 运行中介

r - 按两个或多个列表的元素应用函数

r - 矩阵计算的操作系统之间的巨大性能差异

r - 在 R 中绘制按时间显示日期的折线图

r - R 中的哪个函数从 .wav 文件中提取 dB 值

r - curl 包未安装