-2

我有一个列表,其中显示了元素 999。

在此处输入图像描述

我需要将其转换为 data.table ,其中元素编号分配如下:

在此处输入图像描述

尝试了不同的可能解决方案,但似乎没有任何工作正常。

4

2 回答 2

1

这效果更好:

df <- rbindlist(l, fill = TRUE, use.names = TRUE, idcol = "element_number")
于 2018-11-04T23:16:34.293 回答
1

您可以使用do.call('rbind', ...)从列表中获取数据框,并rep()在列表的索引上将times参数设置为sapply(l, nrow)l列表的名称在哪里)以获取所需的元素编号:

# Make an example list
l <- list(data.frame(a = 1:3, b = 4:6), data.frame(a = 7:8, b = 8:9))
l
#> [[1]]
#>   a b
#> 1 1 4
#> 2 2 5
#> 3 3 6
#> 
#> [[2]]
#>   a b
#> 1 7 8
#> 2 8 9
# Get a dataframe from it
df <- do.call('rbind', l)
# Add the element numbers by repeating the indices of the list,
# each as many times as the number of rows in that element's dataframe
df$element_number <- rep(seq_along(l), times = sapply(l, nrow))
df
#>   a b element_number
#> 1 1 4              1
#> 2 2 5              1
#> 3 3 6              1
#> 4 7 8              2
#> 5 8 9              2

reprex 包(v0.2.1)于 2018 年 11 月 4 日创建

于 2018-11-04T22:56:12.107 回答