首页 > 解决方案 > 将数据框转换为R中的列表

问题描述

我想将数据框转换为列表。请参阅表 1 中的输入。请参阅表 2 中的输出。当您从环境中打开 R 中的列表时。名称 - 以下名称 clus1、clus2... 类型 - 应包含列 V1 中的值 值 - 长度为 3 的列表

Table 1
      V1 V2 V3
clus1 10 a  d
clus2 20 b  e
clus3 5  c  f

Table 2
$`clus1`
[1] "a"  "d" 

$`clus2`
[2] "b"  "e" 

$`clus3`
[2] "c"  "f"

标签: rlistdataframe

解决方案


t1 = read.table(text = "      V1 V2 V3
clus1 10 a  d
clus2 20 b  e
clus3 5  c  ''", header = T)

result = split(t1[, 2:3], f = row.names(t1))
result = lapply(result, function(x) {
  x = as.character(unname(unlist(x)))
  x[x != '']})
result
# $clus1
# [1] "a" "d"
# 
# $clus2
# [1] "b" "e"
# 
# $clus3
# [1] "c"

在这种特殊情况下,如果我们先转换为矩阵,我们可以更直接一点:

r2 = split(as.matrix(t1[, 2:3]), f = row.names(t1))
r2 = lapply(r2, function(x) x[x != ''])
# same result

推荐阅读