r语言 - 在将列表转换为数据帧时包括项目编号



>我正在尝试将项目列表转换为数据框,并将项目编号与数据框中的新行一起保留。

我想保留 6 个标本的前 1800 行数据,但数据以列表形式返回。当我将列表转换为数据框时,由于某些项目在批处理过程中未返回任何数据,因此未显示在新数据框中,因此无法跟踪哪些行来自哪些项目。我粘贴了下面列表中的前 6 项的数据。

-我的工作流程如下:

out <-lapply(out, head)
out
[[1]]
ID sequencedescription             database           citation
1  MNAG563-08              COI-5P BOLD: Public Records BOLD Systems, 2016
2  MNAG564-08              COI-5P BOLD: Public Records BOLD Systems, 2016
3  IAWL696-09              COI-5P BOLD: Public Records BOLD Systems, 2016
4 LPOKD816-10              COI-5P BOLD: Public Records BOLD Systems, 2016
5  GMEM065-11              COI-5P BOLD: Public Records BOLD Systems, 2016
6 GMGSA075-12              COI-5P BOLD: Public Records BOLD Systems, 2016
taxonomicidentification similarity
1             Lepidoptera          1
2             Lepidoptera          1
3             Lepidoptera          1
4             Lepidoptera          1
5             Lepidoptera          1
6             Lepidoptera          1
specimen_country specimen_lat specimen_lon
1    United States       39.717          -78
2    United States       38.991      -77.235
3    United States        30.08      -97.167
4    United States        36.74       -95.95
5    United States      33.4156     -89.2606
6    United States      35.6859     -83.4986
...
[[5]]
ID sequencedescription             database           citation
1   MEC818-04              COI-5P BOLD: Public Records BOLD Systems, 2016
2 RDLQE057-06              COI-5P BOLD: Public Records BOLD Systems, 2016
3  LNCB034-06              COI-5P BOLD: Public Records BOLD Systems, 2016
4 RDLQI742-09              COI-5P BOLD: Public Records BOLD Systems, 2016
5 RDLQI756-09              COI-5P BOLD: Public Records BOLD Systems, 2016
6 BBLSW607-09              COI-5P BOLD: Public Records BOLD Systems, 2016
taxonomicidentification similarity
1             Lepidoptera          1
2             Lepidoptera          1
3             Lepidoptera          1
4             Lepidoptera          1
5             Lepidoptera          1
6             Lepidoptera          1
specimen_country specimen_lat specimen_lon
1           Canada      45.3967      -75.849
2           Canada       45.465      -73.075
3    United States       34.768      -76.764
4           Canada      49.2417      -72.423
5           Canada      45.4998     -76.3522
6    United States       33.883      -96.821
[[6]]
NULL

-然后我转换为数据帧

out_frame <- do.call("rbind", lapply(out, data.frame))

-然后写入 xlsx 文件并首先尝试将 ID #1 分配给前 6 行,将 ID #2 分配给接下来的 6 行,依此类推,但由于第 6 项返回 NULL,因此它没有对齐。

下面是使用数据框列表的解决方案:

out <- list(
data.frame(a=10:30, b=20:40),
data.frame(a=10:50, b=20:60),
NULL
)
out2 <- lapply(seq(along=out), function(i) {
df <- out[[i]]
if(!is.null(df)) df$ID <- i
df
})
out_frame <- do.call(rbind, lapply(out2, head))
out_frame

感谢您的回复。我能够尝试几件事,发现在读取数据时使用setNames函数在请求输出之前分配我的原始 ID 时stringsAsFactors = FASLE设置效果很好。然后将输出转换为数据帧并写入 xlsx 时,原始 ID 保留在第一列中。

最新更新