防止列表编号出现在 do.call(“cbind.data.frame”, my_list) 之后的列名中

Prevent the list number to appear in column names after do.call("cbind.data.frame", my_list)

提问人:LulY 提问时间:6/29/2023 最后编辑:QuintenLulY 更新时间:6/29/2023 访问量:23

问:

我经常在打电话后使用,通常我不会遇到任何问题。由于某种原因,在以下列表中,绑定它们后列名不同;列表编号位于名称之前。do.call("cbind.data.frame", my_list)lapply()

我的列表是这样的:

dput(my_list)

list(`1` = structure(list(`Pulmonary_embolism~f.20002.0` = NA, 
`Pulmonary_embolism~f.20002.1` = NA, `Pulmonary_embolism~f.20002.2` = NA, 
`Pulmonary_embolism~f.20002.3` = NA, `Pulmonary_embolism~f.20002.all` = NA), row.names = "1", class = "data.frame"), 
`2` = structure(list(`Pulmonary_embolism~f.6152.0` = NA, 
    `Pulmonary_embolism~f.6152.1` = NA, `Pulmonary_embolism~f.6152.2` = NA, 
    `Pulmonary_embolism~f.6152.3` = NA, `Pulmonary_embolism~f.6152.all` = NA), row.names = "1", class = "data.frame"))

但是在变量改变之后:do.call("cbind.data.frame", my_list)

names(do.call("cbind.data.frame", my_list))

[1] "1.Pulmonary_embolism~f.20002.0"   "1.Pulmonary_embolism~f.20002.1"   "1.Pulmonary_embolism~f.20002.2"   "1.Pulmonary_embolism~f.20002.3"   "1.Pulmonary_embolism~f.20002.all"
[6] "2.Pulmonary_embolism~f.6152.0"    "2.Pulmonary_embolism~f.6152.1"    "2.Pulmonary_embolism~f.6152.2"    "2.Pulmonary_embolism~f.6152.3"    "2.Pulmonary_embolism~f.6152.all"

如何防止列名的列表编号部分出现?

r 列出 数据绑定 名称

评论


答:

1赞 Quinten 6/29/2023 #1

首先,您可以使用 with 提取列名称,并确保使用 删除列名称中数据帧的名称。之后,您可以将这些名称用于输出,如下所示:lapplyunlistuse.names=FALSEdo.call

your_names = unlist(lapply(my_list, \(x) colnames(x)), use.names = FALSE)
df = do.call("cbind.data.frame", my_list)
names(df) = your_names
df
#>   Pulmonary_embolism~f.20002.0 Pulmonary_embolism~f.20002.1
#> 1                           NA                           NA
#>   Pulmonary_embolism~f.20002.2 Pulmonary_embolism~f.20002.3
#> 1                           NA                           NA
#>   Pulmonary_embolism~f.20002.all Pulmonary_embolism~f.6152.0
#> 1                             NA                          NA
#>   Pulmonary_embolism~f.6152.1 Pulmonary_embolism~f.6152.2
#> 1                          NA                          NA
#>   Pulmonary_embolism~f.6152.3 Pulmonary_embolism~f.6152.all
#> 1                          NA                            NA

另一种选择是使用 from 在名称中没有数字,如下所示:bind_colsdplyr

library(dplyr)

bind_cols(my_list)
#>   Pulmonary_embolism~f.20002.0 Pulmonary_embolism~f.20002.1
#> 1                           NA                           NA
#>   Pulmonary_embolism~f.20002.2 Pulmonary_embolism~f.20002.3
#> 1                           NA                           NA
#>   Pulmonary_embolism~f.20002.all Pulmonary_embolism~f.6152.0
#> 1                             NA                          NA
#>   Pulmonary_embolism~f.6152.1 Pulmonary_embolism~f.6152.2
#> 1                          NA                          NA
#>   Pulmonary_embolism~f.6152.3 Pulmonary_embolism~f.6152.all
#> 1                          NA                            NA

创建于 2023-06-29 with reprex v2.0.2