我想将数据框转换为列表。请参见表1中的输入。请参见表2中的输出。从环境中打开R中的列表时。名称-以下名称clus1,clus2 ...类型-应包含列V1中的值值-长度为3的列表
Table 1
V1 V2 V3
clus1 10 a d
clus2 20 b e
clus3 5 c f
Run Code Online (Sandbox Code Playgroud)
Table 2
$`clus1`
[1] "a" "d"
$`clus2`
[2] "b" "e"
$`clus3`
[2] "c" "f"
Run Code Online (Sandbox Code Playgroud)
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"
Run Code Online (Sandbox Code Playgroud)
在这种特殊情况下,如果先转换为矩阵,我们可以直接进行以下操作:
r2 = split(as.matrix(t1[, 2:3]), f = row.names(t1))
r2 = lapply(r2, function(x) x[x != ''])
# same result
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
48 次 |
| 最近记录: |