You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言:如何将含多行的列表转换为多列?

列表转置为多列的解决方案

问题说明

需要将包含两行(名称行+数值行)的列表转换为多列矩阵格式,具体数据、目标格式及已尝试代码如下:

当前数据

$`1`
    may  servic    busi    oper product 
     98      82      65      59      51 

$`2`
    health  care    serv    busi state 
     99      80      66      57      49 

$`3`
    compani  servic    busi    can market 
     96      76      65      58      50 

目标格式

[,1]      [,2]      [,3]         [,4]         [,5]          [,6] [,7] [,8] [,9] [,10]
1  "may"     "servic"  "busi"       "oper"       "product"     98   82   65   59   51   
2  "health"     "care"  "serv"       "busi"       "state"     99   80   66   57   49   
3  "compani"     "servic"  "busi"       "can"       "market"     96   76   65   58   50   

已尝试代码

list <- 
  do.call(rbind, lapply(top_5, function(x) 
    { x <- names(x); length(x) <- 5; x } ))

可行转换方法

方法1:生成字符型矩阵

遍历列表每个元素,将元素的名称和对应数值拼接为向量,再按行绑定成矩阵:

# 假设列表对象名为top_5
result_matrix <- do.call(rbind, lapply(top_5, function(x) {
  c(names(x), as.character(x))
}))

# 打印结果即可呈现目标格式
print(result_matrix)

方法2:生成混合类型数据框

如果需要保留数值部分的数值类型,可创建数据框:

result_df <- do.call(rbind, lapply(top_5, function(x) {
  data.frame(
    col1 = names(x)[1], col2 = names(x)[2], col3 = names(x)[3],
    col4 = names(x)[4], col5 = names(x)[5],
    col6 = x[1], col7 = x[2], col8 = x[3], col9 = x[4], col10 = x[5],
    stringsAsFactors = FALSE,
    row.names = NULL
  )
}))

内容的提问来源于stack exchange,提问作者tctrg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 11:05:09