r - 将数据框转换为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"
解决方案
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
推荐阅读
- javascript - 如何删除 metricsgraphs.js 折线图下方/上方的黑色区域?
- file - 在课堂上保存文件或频道的好习惯
- python-3.x - TypeError: unhashable type: 'numpy.ndarray' (k 表示聚类)
- istio - Istio 网格因“重复条目”错误而中断
- javascript - 如何使用角度foreach返回值?
- mysql - 如何在 SQL 查询中连接同一表中的列以将它们显示为一个?
- sql - 如何通过数据库查询直接访问产品名称、产品价格和永久链接和产品照片列
- html - CSS Navbar 子菜单如何居中?
- wordpress - Wordpress 查询仅返回 1 个结果,但所有结果都带有 nonpaging = true
- image - 为什么 imfindcircles 在尝试在具有密集圆圈的图像中查找圆圈时不起作用?