【问题标题】:How to set rownames as column in the list of dataframes?如何将行名设置为数据框列表中的列?
【发布时间】:2021-02-25 13:38:10
【问题描述】:

我在全局环境中有名为 ma​​tch_list 的匹配数据的数据框列表(列表 4)。我想用match_list <- lapply(match_list,t) 转置列表,以便将指标作为列名。

它转置了每个列表中的数据框,但它也将以前的列名作为行名。你能帮我摆脱行名吗?并使其成为标准列?

然后我正在执行 for 循环

#### create individual dataframes ----
for (i in seq(match_list))
  assign(paste0(file_names[[i]]), match_list[[i]])

在我的全局环境中创建单独的数据框

我尝试了几种方法,但仍然无法转过头来使其发挥作用。

我的尝试:

match_list <- lapply(match_list,function(x){
  
  colnames(x) <- rownames_to_column(match_list[[1]]) 
  
})

这是我的整个脚本:

match_xlsx <- as_tibble(list.files("C:/Users/User/Desktop/asJohan", pattern = ".xlsx", full.names = TRUE, all.files = FALSE))
file_names <- list.files("C:/Users/User/Desktop/asJohan", pattern = ".xlsx", full.names = TRUE, all.files = FALSE)


#### read specific sheet from excel ---- create two lists and merge them
match_list <- lapply(match_xlsx$value, read_excel, sheet = 1, range = "B1:N40")
match_list <- lapply(match_list,t) 
#match_list <- lapply(match_list, function(x) {x <- x[-1,-1 ]}) #### remove first column and row




###set first row as a header - column names
match_list <- lapply(match_list, function(x){
colnames(x) <- x[1,]
x[-(1:3),]})

####set rowname as column name

match_list <- lapply(match_list, rownames_to_column, var='former_transposed_colnames')


#### create individual dataframes ----
for (i in seq(match_list))
assign(paste0(file_names[[i]]), match_list[[i]])```

【问题讨论】:

    标签: r list dataframe


    【解决方案1】:

    函数rownames_to_column(如果来自tibble-package),返回输入的data.frame,在这种情况下,是match_list[[1]]中的那个。相反,您试图将整个 data.frame 推入 colnames 的向量(colnames(x) &lt;--portion)。

    相反,您可以简单地使用

    match_list <- lapply(match_list, rownames_to_column)
    

    rownames_to_column 的默认行为会将行名分配给名为rownames 的列。您可以使用例如更改此设置

    match_list <- lapply(match_list, rownames_to_column, var='former_transposed_colnames')
    

    编辑:

    您可以使用...lapply:

    将您的列表转换回 data.frames
    match_list <- lapply(match_list,t)
    match_list <- lapply(match_list,as.data.frame)
    match_list <- lapply(match_list, rownames_to_column)
    
    # or if you load dplyr 
    library(dplyr)
    match_list <- lapply(match_list, t) %>%
      lapply(as.data.frame) %>%
      lapply(rownames_to_column)
    

    但不要使用t 转置(因为它要求所有条目具有相同的data.type,即所有内容都变成字符,因为列是字符串,请尝试使用tidyrpivot_longerpivot_wider . 但是,这将要求您有一个 id 列(在pivot_longer 之前),但我怀疑您可能已经在第一列中有一个(在“A”列中,您有时会删除它)。如果你没有,您可以通过简单地对行编号来创建一个虚拟 id 列。完成后,删除虚拟值。

    【讨论】:

    • 您好,感谢您抽时间回答。我已经测试过了,但我对 rownames_to_column() 有疑问,因为它仅适用于数据帧。你认为我可以通过 rowname_to_column 传递列表,因为它给了我这个错误 FUN(X[[i]], ...) 中的错误:is.data.frame(df) is not TRUE
    • 我看到了错误;我想念你在所有 data.frames 上使用了 t - t only 返回矩阵。所以我目前的解决方案行不通。
    • 没问题,我已经添加了对更新我的整个脚本外观的质疑。我已经使用 t() 进行转置。非常感谢
    • @MrGrumble - 非常感谢您的帮助!太棒了。
    猜你喜欢
    • 2018-12-14
    • 2020-06-05
    • 2022-11-13
    • 2018-12-17
    • 2019-05-26
    • 2022-01-14
    • 2020-07-17
    • 1970-01-01
    • 2021-02-15
    相关资源
    最近更新 更多